dongye9071 2016-05-17 04:34 采纳率: 0%
浏览 28
已采纳

函数是否必须满足函数类型的确切签名?

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?

  • 写回答

1条回答 默认 最新

  • duanguangwang5829 2016-05-17 04:44
    关注

    Yes, a function has to satisfy the exact signature of the function type. Similar things come up in other contexts: a more formal way to say it is that generally types in Go lack covariance. Here, you could wrap json.NewEncoder in a function returning MyEncoder.

    I'd use the value type MyEncoder not the pointer *MyEncoder because if you store a pointer inside the interface value then generally you don't also need a pointer to the interface value just to avoid copies; here's more on pointers vs. values if it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog