Difference between method signatures of structs - go

As a programmer coming from other languages like C++, I find it rather strange that go allows to specify methods for structs that allow either a pointer or an instance as a parameter. According to go by example once could use either of them if we didn't want to modify the origin:
Go automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on method calls or to allow the method to mutate the receiving struct.
Consider the following code:
package main
import (
"fmt"
)
type Foo struct {}
type Bar struct {}
func (this Foo) String() string {
return "Foo"
}
func (this *Bar) String() string {
return "Bar"
}
func main() {
fmt.Println(Foo{}) // "Foo"
fmt.Println(Bar{}) // "{}"
}
Why can't I use both signature versions to modify the stringify (I don't know how it is actually called in go) behavior of the structs?
Just to be clear: I don't really care about the stringify, but want to understand how the language behaves.

Just add & to the Bar{} and make it pointer receiver, like this:
fmt.Println(&Bar{}) // "Bar"
Here a little adjustment to your code that outputs:
Foo
Bar
see:
package main
import "fmt"
type Foo struct{}
func (Foo) String() string {
return "Foo"
}
type Bar struct{}
func (*Bar) String() string {
return "Bar"
}
func main() {
fmt.Println(Foo{}) // "Foo"
pb := &Bar{}
fmt.Println(pb) // "Bar"
}
Notes:
Receiver name should be a reflection of its identity; don't use
generic names such as "this" or "self"
And you don't need names here for your example.
And nice to read Golang methods receivers:
Value receivers operate on a copy of the original type value. This
means that there is a cost involved, especially if the struct is very
large, and pointer received are more efficient.

Because Bar does not implement stringer *Bar does.
If you remove implementation of stringer from Foo, you will get "{}".
Similarly, When you write fmt.Println(Bar{}) it means it will look for something like func (Bar) String() and not func (*Bar) String()
Additioanlly , story is different when you write fmt.Println(&Foo{}), you might think it will print "{}" because there is no func (*Foo) String() but it will print "Foo".
For that, you will have to understand Interfaces. These are my experiences so please do your own research too. The fmt.Print function calls String() on passed arguments. So actually the String() is not called on your struct but rather than an variable of type stringer.
interface type can hold a type(which implemented it) or pointer to it,
if it was implemented with value receiver. That is why Foo{} and
&Foo{} both work.
interface type can hold a type's pointer (which implemented it)only,
if it was implemented with pointer receiver. Why? Because when you
implement an interface with pointer receiver, it needs an address
which can only be provided with a pointer. That is why only &Bar{}
works and not Bar{}

Related

Cannot use variable of type *T as type in argument

I'm learning Go 1.18 generics and I'm trying to understand why I'm having trouble here. Long story short, I'm trying to Unmarshal a protobuf and I want the parameter type in blah to "just work". I've simplified the problem as best I could, and this particular code is reproducing the same error message I'm seeing:
./prog.go:31:5: cannot use t (variable of type *T) as type stringer in argument to do:
*T does not implement stringer (type *T is pointer to type parameter, not type parameter)
package main
import "fmt"
type stringer interface {
a() string
}
type foo struct{}
func (f *foo) a() string {
return "foo"
}
type bar struct{}
func (b *bar) a() string {
return "bar"
}
type FooBar interface {
foo | bar
}
func do(s stringer) {
fmt.Println(s.a())
}
func blah[T FooBar]() {
t := &T{}
do(t)
}
func main() {
blah[foo]()
}
I realize that I can completely simplify this example by not using generics (i.e., pass the instance to blah(s stringer) {do(s)}. However, I do want to understand why the error is happening.
What do I need to change with this code so that I can create an instance of T and pass that pointer to a function expecting a particular method signature?
In your code there's no relationship between the constraints FooBar and stringer. Furthermore the methods are implemented on the pointer receivers.
A quick and dirty fix for your contrived program is simply to assert that *T is indeed a stringer:
func blah[T FooBar]() {
t := new(T)
do(any(t).(stringer))
}
Playground: https://go.dev/play/p/zmVX56T9LZx
But this forgoes type safety, and could panic at run time. To preserve compile time type safety, another solution that somewhat preserves your programs' semantics would be this:
type FooBar[T foo | bar] interface {
*T
stringer
}
func blah[T foo | bar, U FooBar[T]]() {
var t T
do(U(&t))
}
So what's going on here?
First, the relationship between a type parameter and its constraint is not identity: T is not FooBar. You cannot use T like it was FooBar, therefore *T is definitely not equivalent to *foo or *bar.
So when you call do(t), you're attempting to pass a type *T into something that expects a stringer, but T, pointer or not, just does not inherently have the a() string method in its type set.
Step 1: add the method a() string into the FooBar interface (by embedding stringer):
type FooBar interface {
foo | bar
stringer
}
But that's not enough yet, because now none of your types actually implement it. Both declare the method on the pointer receiver.
Step 2: change the types in the union to be pointers:
type FooBar interface {
*foo | *bar
stringer
}
This constraint now works, but you have another problem. You can't declare composite literals when the constraint doesn't have a core type. So t := T{} is also invalid. We change it to:
func blah[T FooBar]() {
var t T // already pointer type
do(t)
}
Now this compiles, but t is actually the zero value of a pointer type, so it's nil. Your program doesn't crash because the methods just return some string literal.
If you need to also initialize the memory referenced by the pointers, inside blah you need to know about the base types.
Step 3: So you add T foo | bar as one type param, and change the signature to:
func blah[T foo | bar, U FooBar]() {
var t T
do(U(&t))
}
Done? Not yet. The conversion U(&t) is still invalid because the type set of both U and T don't match. You need to now parametrize FooBar in T.
Step 4: basically you extract FooBar's union into a type param, so that at compile time its type set will include only one of the two types:
type FooBar[T foo | bar] interface {
*T
stringer
}
The constraint now can be instantiated with T foo | bar, preserve type safety, pointer semantics and initialize T to non-nil.
func (f *foo) a() string {
fmt.Println("foo nil:", f == nil)
return "foo"
}
func main() {
blah[foo]()
}
Prints:
foo nil: false
foo
Playground: https://go.dev/play/p/src2sDSwe5H
If you can instantiate blah with pointer types, or even better pass arguments to it, you can remove all the intermediate trickery:
type FooBar interface {
*foo | *bar
stringer
}
func blah[T FooBar](t T) {
do(t)
}
func main() {
blah(&foo{})
}

How to assign a pointer to interface in Go

package main
import "fmt"
type intr interface {
String() string
}
type bar struct{}
func (b *bar) String() string {
return "bar"
}
type foo struct {
bar *intr
}
func main() {
bar1 := bar{}
foo1 := foo{bar: &bar1}
fmt.Println(foo1)
}
I get a compile-time error:
cannot use &bar1 (type *bar) as type *intr in field value: *intr is pointer to interface, not interface
Why is this error happened?
How to assign foo.bar?
You're assigning it to a pointer to the interface. After changing the field type to interface it will work:
type foo struct {
bar intr
}
Pointers to interfaces are quite rarely needed.
Uber-go style guide pointers-to-interfaces contains exact answer to your question,
You almost never need a pointer to an interface. You should be passing interfaces as values—the underlying data can still be a pointer. An interface is two fields: A pointer to some type-specific information. You can think of this as "type."
And a data pointer. If the data stored is a pointer, it’s stored directly. If the data stored is a value, then a pointer to the value is stored.
If you want interface methods to modify the underlying data, you must use a pointer.
My recommendation is to get acquainted with it as soon as possible,
Hope it helps

Given a method value, get receiver object

Is there a way in Go, to get the receiver object from a method value?
For example, is there any such MagicFunc that would make the following program output the string my info from the underlying Foo instance.
package main
import "fmt"
type Foo struct {
A string
}
func (foo *Foo) Bar() string {
return "bar"
}
func MyFunc(val interface{}) {
i := MagicFunc(val)
f := i.(Foo)
fmt.Println(f.A)
}
func main() {
f := Foo{A: "my info"}
MyFunc(f.Bar)
}
No, it is not possible to get the method's receiver instance.
The most you can get is the receiver's type if you use a method expression instead of method value but that won't help you get the my info string.
I wanted to deep-dive into this a bit and soon found this document: https://golang.org/s/go11func
As describe there, when MyFunc is entered val doesn't contain a reference to f.Bar but rather to a special function with the signature func() string. That function knows that it can retrieve the orignal f pointer by checking the well-known R0 register (in the example. On amd64 it appears to be dx, but that's an implementation detail obviously).
Thus there's no way to do this without using implementation specific assembly code, which would be very fragile.

Get method receiver with reflect [duplicate]

Is there a way in Go, to get the receiver object from a method value?
For example, is there any such MagicFunc that would make the following program output the string my info from the underlying Foo instance.
package main
import "fmt"
type Foo struct {
A string
}
func (foo *Foo) Bar() string {
return "bar"
}
func MyFunc(val interface{}) {
i := MagicFunc(val)
f := i.(Foo)
fmt.Println(f.A)
}
func main() {
f := Foo{A: "my info"}
MyFunc(f.Bar)
}
No, it is not possible to get the method's receiver instance.
The most you can get is the receiver's type if you use a method expression instead of method value but that won't help you get the my info string.
I wanted to deep-dive into this a bit and soon found this document: https://golang.org/s/go11func
As describe there, when MyFunc is entered val doesn't contain a reference to f.Bar but rather to a special function with the signature func() string. That function knows that it can retrieve the orignal f pointer by checking the well-known R0 register (in the example. On amd64 it appears to be dx, but that's an implementation detail obviously).
Thus there's no way to do this without using implementation specific assembly code, which would be very fragile.

How to hide the default type constructor in golang?

The reason I have this question is that I often make mistakes that I forgot to specify a value to a struct's field, then the compiler is fine, but the zero value causes bugs.
Here is an example. Say I have a type Foo defined like this in a package:
package types
type Foo struct {
RequiredField1 string
RequiredField2 string
}
It is exposed and has 2 fields that I'd like both of them to be specified when the Foo struct is created.
Then I can import and use it in my main function like this:
package main
import (
"github.com/foo/bar/types"
)
func main() {
f := &Foo{
RequiredField1: "fff",
}
fmt.Printf("f.RequiredField2: %v", f.RequiredField2)
}
This causes a bug because I forgot to specify RequiredField2 which is required. And I often make this kind of bugs :p
Now, in order to leverage the compile and prevent this mistake, I made a constructor function for Foo and asks for the required values.
func NewFoo(field1 string, field2 string) *Foo {
return &Foo{Field1: field1, Field2: field2}
}
So that if I forgot to pass field2, the compiler won't compile my code:
func main() {
f := NewFoo("foo")
fmt.Printf("f.Field2: %v", f.Field2)
}
The build will fail:
./prog.go:18:13: not enough arguments in call to NewFoo
have (string)
want (string, string)
Now the question is: how to stop the foreign callers (callers from other namespaces) from calling the default constructor of Foo, that is &Foo, and force them to use the NewFoo?
If I can, then I'm safe since NewFoo is the only way to create the Foo type and the compiler helps me ensure all fields are present when calling it.
You can avoid this problem by making Foo type unexported.
You can make an interface that is Exported and has all the methods that Foo type performs.
Example:-
type Foo interface{
DoSomething()
}
type foo struct{
RequiredField1 string
RequiredField2 string
}
func NewFoo(requiredField1 string,requiredField2 string)*foo{
return &foo{
RequiredField1:requiredField1,
RequiredField2:requiredField2,
}
}
func (f *foo)DoSomething(){
// your implementation
}
In this way all the caller will be able to access it but cannot create foo without NewFoo function.
How to hide the default type constructor in golang?
You cannot for an exported type.
Get used to it, it is not a problem in real life.
(For unexported types, just provide a func NewUnexportedType(...) unexportedType. )
Effective Go
it's helpful to arrange when designing your data structures that the
zero value of each type can be used without further initialization.
we often need to change the type definition, like adding more fields
That is why you should make the zero value for struct fields significant. The behavior is by design. For example, it is used to maintain the Go 1 compatibility guarantee.

Resources