why cannot use (type func(string)) as type func(interface{}) in assignment

五迷三道 提交于 2021-02-05 12:37:50

问题


Please first have a look at the code below.

package main

import "fmt"

type InterfaceFunc func(interface{})
type StringFunc func(string)

func stringFunc(s string) {
    fmt.Printf("%v", s)
}

func interfaceFunc(i interface{}) {
    fmt.Printf("%v", i)
}

func main() {
    var i = interfaceFunc
    var s = stringFunc

    i = s // I would like someone to explain why this can't be done exactly.
}

Run at https://play.golang.org/p/16cE4O3eb95

Why an InterfaceFunc can't hold a StringFunc while an interface{} can hold a string.


回答1:


You can not do s = i or i = s, and the reason is both functions are of different type (different signatures), you can not just assign one type with another in golang.

Also type InterfaceFunc func(interface{}) type StringFunc func(string) are sitting there doing nothing.



来源:https://stackoverflow.com/questions/54101145/why-cannot-use-type-funcstring-as-type-funcinterface-in-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!