Golang : cannot assign type int to value (type uint8) in range error
Sometimes, we tend to overlook a small part of for--loop just because we use it frequently and expect the compiler or linker to alert us of the problem before run time. The problem described below is only visible during run time :
Problem :
You get an error message that look like this :
cannot assign type int to value (type uint8) in range
or something similar when trying to use range. For example :
package main
import "fmt"
func main() {
var xs []uint8 = []uint8{123, 124, 125}
var value uint8
for value = range xs {
fmt.Println(value)
}
}
Solution :
That is because, range over a slice or array will return 2 values.... but yet the code will compile will issue! To fix this error. Change the codes to :
package main
import "fmt"
func main() {
var xs []uint8 = []uint8{123, 124, 125}
var value uint8
for _, value = range xs { // ignore the key
fmt.Println(value)
}
}
or
package main
import "fmt"
func main() {
var xs []uint8 = []uint8{123, 124, 125}
var key uint8
var value uint8
for key, value = range xs { // assign the key to a variable.
fmt.Println(key, value)
}
}
output :
0 123
1 124
2 125
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.9k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+9k Golang : On lambda, anonymous, inline functions and function literals
+14.1k Golang : Get dimension(width and height) of image file
+16.3k Golang : How to check if input from os.Args is integer?
+8.1k Golang Hello World Example
+17.2k Golang : Set up source IP address before making HTTP request
+8.6k Golang : Convert word to its plural form example
+14.7k Golang : Execute function at intervals or after some delay
+9.6k Facebook : Getting the friends list with PHP return JSON format
+10.2k Golang : Test a slice of integers for odd and even numbers
+11k Golang : Natural string sorting example
+21.1k Golang : Underscore or snake_case to camel case example