If I have:
type foo struct{ } func bar(baz interface{}) { }
The above are set in stone - I can't change foo or bar. Additionally, baz must converted back to a foo struct pointer inside bar. How do I cast &foo{} to interface{} so I can use it as a parameter when calling bar?
interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.
We can define interfaces considering the different actions that are common between multiple types. In Go, we can automatically infer that a struct (object) implements an interface when it implements all its methods.
Structs and interfaces are Go's way of organizing methods and data handling. Where structs define the fields of an object, like a Person's first and last name. The interfaces define the methods; e.g. formatting and returning a Person's full name.
Implementing an interface on a struct has no negative consequences whatsoever. Any variable of the interface type used to hold a struct will result in a boxed value of that struct being used.
Structure Pointer: It is defined as the pointer which points to the address of the memory block that stores a structure is known as the structure pointer. Below is an example of the same: In the above code s is an instance of struct point and ptr is the struct pointer because it is storing the address of struct point.
Any code that has a pointer through which it can access the array can call the methods in that interface. Speaking precisely about this multiple indirection is inconvenient, so instead, the pointer to the interface function table that another object must have to call its methods is called simply an interface pointer.
Structure Pointer: It is defined as the pointer which points to the address of the memory block that stores a structure is known as the structure pointer. Below is an example of the same:
Similarly, we can have a pointer to structures, where a pointer variable can point to the address of a structure variable. Here is how we can declare a pointer to a structure variable.
To turn *foo
into an interface{}
is trivial:
f := &foo{} bar(f) // every type implements interface{}. Nothing special required
In order to get back to a *foo
, you can either do a type assertion:
func bar(baz interface{}) { f, ok := baz.(*foo) if !ok { // baz was not of type *foo. The assertion failed } // f is of type *foo }
Or a type switch (similar, but useful if baz
can be multiple types):
func bar(baz interface{}) { switch f := baz.(type) { case *foo: // f is of type *foo default: // f is some other type } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With