Skip to content

Instantly share code, notes, and snippets.

@dlsniper
Last active February 24, 2018 16:02
Show Gist options
  • Save dlsniper/fa727b40ab21fd7c5b2362caca8e1526 to your computer and use it in GitHub Desktop.
Save dlsniper/fa727b40ab21fd7c5b2362caca8e1526 to your computer and use it in GitHub Desktop.

This proposal would lead to interfaces forcing structs as types to implement them, whereas today it's possible to have the implementation be a completely different type, like a func or a string, for example, see https://play.golang.org/p/irTsnlldaea as an example for this.

package main

import "fmt"

type (
	demo    func()
	hello   string
	Helloer interface {
		Hello()
	}
)

func (demo) Hello() {
	fmt.Println("Hello, playground")
}

func (h hello) Hello() {
	fmt.Println("Hello, " + h)
}

func call(h Helloer) {
	h.Hello()
}

func main() {
	d := demo(func() {})
	call(d)

	h := hello("world")
	call(h)
}

If the problem is accepting a restricted, common subset of fields, maybe a different venue to pursue this would be to allow passing of structs that get narrowed down to a subset of the fields. For example, maybe this would be a way to solve passing data around: https://play.golang.org/p/57BBaoUlMhu

package main

import "fmt"

type (
	BaseStruct struct {
		F2 string
	}

	Struct1 struct {
		F1, F2 string
	}

	Struct2 struct {
		F2, F3 string
	}
)

func call(b BaseStruct) {
	fmt.Printf("f2: %v\n", b.F2)
}

func main() {
	s1 := Struct1{
		F1: "f1",
		F2: "f2",
	}
	call(s1)

	s2 := Struct2{
		F2: "f2",
		F3: "f3",
	}
	call(s2)
}

Obviously, this does not solve the problem of calling methods on the type itself. I can't think of any better answer than: if data is needed, accept a common struct, if functionality is needed, accept an interface.

One could say: why not use embedding of BaseStruct in the Struct1 and Struct2. Obviously, embedding would be preferable but in this case please assume that Struct1 and Struct2 are coming from two different place which the author does not full control over.

Reading / writing into the fields of BaseStruct should be passthrough to the value that was used to call the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment