Checking the equality of two slices

You should use reflect.DeepEqual() DeepEqual is a recursive relaxation of Go’s == operator. DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal. Array values are deeply equal when their … Read more

What should be the values of GOPATH and GOROOT?

GOPATH is discussed in the cmd/go documentation: The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list. GOPATH must be set to get, build and install packages outside the standard … Read more

When is the init() function run?

Yes assuming you have this: var WhatIsThe = AnswerToLife() func AnswerToLife() int { // 1 return 42 } func init() { // 2 WhatIsThe = 0 } func main() { // 3 if WhatIsThe == 0 { fmt.Println(“It’s all a lie.”) } } AnswerToLife() is guaranteed to run before init() is called, and init() is … Read more

How to find the type of an object in Go?

The Go reflection package has methods for inspecting the type of variables. The following snippet will print out the reflection type of a string, integer and float. package main import ( “fmt” “reflect” ) func main() { tst := “string” tst2 := 10 tst3 := 1.2 fmt.Println(reflect.TypeOf(tst)) fmt.Println(reflect.TypeOf(tst2)) fmt.Println(reflect.TypeOf(tst3)) } Output: Hello, playground string int … Read more

How can I convert a zero-terminated byte array to string?

Methods that read data into byte slices return the number of bytes read. You should save that number and then use it to create your string. If n is the number of bytes read, your code would look like this: s := string(byteArray[:n]) To convert the full string, this can be used: s := string(byteArray[:len(byteArray)]) … Read more