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
+10.3k Golang : How to flush a channel before the end of program?
+10.6k Golang : Handle API query by curl with Gorilla Queries example
+14.9k Golang : convert string or integer to big.Int type
+6.3k Golang : Calculate how many weeks left to go in a given year
+4.8k Javascript : How to replace HTML inside <div>?
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+6.3k Golang : Dealing with struct's private part
+8k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+6.6k Gogland : Single File versus Go Application Run Configurations
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+4k HTTP common errors and their meaning explained