Go.Tips
12 subscribers
7 photos
15 links
Useful tips, libraries and information for Go (Golang) developers

Rust::Tips: @rust_code_tips
My GitHub: https://github.com/ankddev
Download Telegram
Check that Interface value is equal to nil
If interface contains nil, it can be not equal nil, e.g.
func main() { 
var x interface{}
var y *int = nil
x = y

if x != nil {
fmt.Println("x != nil") // <-- actual
} else {
fmt.Println("x == nil")
}
fmt.Println(x) } // x != nil // <nil>

prints
x != nil
<nil>

To correctly check if interface is equal to nil, you can write function, similar to
func IsNil(x interface{}) bool {
if x == nil {
return true
}

return reflect.ValueOf(x).IsNil()
}

This function will work as expected.
#tip #example
@golang_tips
new vs make
Both make() and new() are used for memory allocation. But make() returns initialized type value, while new() returns nil-pointer to type.
a := new(chan int) // a has *chan int type
b := make(chan int) // b has chan int type

#tip #example
@golang_tips