Consider the following simple go program
package main
import (
"io"
"encoding/json"
"os"
)
type MyEncoder interface {
Encode(v interface{}) error
}
type MyEncoderCreator func(io.Writer) *MyEncoder
type MyContainer struct {
Creator MyEncoderCreator
}
func main() {
container := Container{
Creator:json.NewEncoder,
}
encoder := container.Creator(os.Stdout)
encoder.Encode(map[string]string{"key":"value"})
}
This program fails to compile with the following error:
./main.go:21: cannot use json.NewEncoder (type func(io.Writer) *json.Encoder) as type MyEncoderCreator in field value
Why is this? The json.Encoder
struct has a receiver that satisfies the MyEncoder
interface. So should the json.NewEncoder
function be allowed to assigned to MyContainer.Creator
?