Test for nil values in nested stucts

One elegant way (in my opinion) of handling it is to add getters to structs that are used as pointers. This “technique” is also used by the generated Go code of protobuf, and it allows natural chaining of method calls without having to worry about runtime panic due to nil pointers. In your example the … Read more

Go equivalent of a void pointer in C

According to the Go Programming Language Specification: A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface: interface{} If you search within that document for interface{}, you’ll see quite a few examples of how you can use it to … Read more

Passing by reference and value in Go to functions

First, Go technically has only pass-by-value. When passing a pointer to an object, you’re passing a pointer by value, not passing an object by reference. The difference is subtle but occasionally relevant. For example, you can overwrite the pointer value which has no impact on the caller, as opposed to dereferencing it and overwriting the … Read more

Range references instead values

The short & direct answer: no, use the array index instead of the value So the above code becomes: package main import “fmt” type MyType struct { field string } func main() { var array [10]MyType for idx, _ := range array { array[idx].field = “foo” } for _, e := range array { fmt.Println(e.field) … Read more

How to check if two variables point to the same object in memory?

There is the function ptr::eq: use std::ptr; struct Foo<‘a> { bar: &’a str, } fn main() { let foo_instance = Foo { bar: “bar” }; let some_vector: Vec<&Foo> = vec![&foo_instance]; assert!(ptr::eq(some_vector[0], &foo_instance)); } Before this was stabilized in Rust 1.17.0, you could perform a cast to *const T: assert!(some_vector[0] as *const Foo == &foo_instance as … Read more