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
+31.5k Golang : How to convert(cast) string to IP address?
+5.5k Golang : Detect words using using consecutive letters in a given string
+4.9k Linux : How to set root password in Linux Mint
+39k Golang : How to read CSV file
+6.8k Mac OSX : Find large files by size
+6k Golang : Extract XML attribute data with attr field tag example
+7k Golang : Get Alexa ranking data example
+5.5k Javascript : How to refresh page with JQuery ?
+5.6k Swift : Get substring with rangeOfString() function example
+12.3k Golang : flag provided but not defined error
+7.4k Golang : Detect sample rate, channels or latency with PortAudio
+7.7k Golang : Getting Echo framework StartAutoTLS to work