« Back to Index

Go: type asserting/coercing

View original Gist on GitHub

Tags: #go

go type asserting coercing.go

/*
bar and baz are structs with pointer reference to a foo struct.
there's a fooer interface for the foo struct
we also have a function that accepts a fooer
the purpose of the function is to coerce the arg from an interface type to a concrete type
*/
package main

import (
	"fmt"
)

type foo struct {
	msg     string
	enabled bool
}

func (f *foo) do(thing string) (string, error) {
	return fmt.Sprintf("done %s -- %s", thing, f.msg), nil
}

type fooer interface {
	do(thing string) (string, error)
}

type bar struct {
	thing *foo
}

type baz struct {
	thing *foo
}

func assignMsg(f fooer) {
	if foothing, ok := f.(*foo); ok {
		foothing.msg = "assigned dynamically"
	}
	fmt.Println(f.do("something here"))
}

func main() {
	br := bar{thing: &foo{enabled: true}}
	bz := baz{thing: &foo{enabled: true}}
	fmt.Printf("br: %+v\n", br)
	fmt.Printf("bz: %+v\n", bz)

	ret, _ := br.thing.do("with bar")
	fmt.Println(ret)

	ret, _ = bz.thing.do("with baz")
	fmt.Println(ret)

	assignMsg(br.thing)
}