简体   繁体   English

接口功能/“ cast”在golang中实际上做什么?

[英]What does the interface function/“cast” actually do in golang?

I'm relatively new to golang, and the project I'm looking at has this sort of pattern repeated several times: 我对golang还是比较陌生,而我正在研究的项目已多次重复这种模式:

package foo

type Foo interface {
    Bar() int
}

type foo struct {
}

func (f *foo) Bar() int {
    return 42
}

func New() Foo {
    // why?
    return Foo(&foo{})
}

If I replace the returns statement in the last function with return &foo{} everything works fine as I expected... it's duck typing if I understand it correctly. 如果我将最后一个函数中的returns语句替换为return &foo{}一切都会按预期进行...如果我正确理解,那就是鸭子输入。 So what is the point of using the Foo(...) function? 那么使用Foo(...)函数有什么意义呢? Using a type as a function seems to work when you're wrapping a built in type such as int in a type that probably has methods. 当您将内置类型(例如int)包装在可能具有方法的类型中时,将类型用作函数似乎可行。 I'm curious as to the author's intent here. 我对作者的意图感到好奇。 If it's covered in the language spec I was unable to find it. 如果语言规范中涵盖了它,我将找不到它。

The expression Foo(x) is a conversion . 表达式Foo(x)是一个conversion The conversion is not needed here because a *foo is assignable to a Foo . 这里不需要转换,因为*foo 可分配Foo The code should be written as: 该代码应写为:

func New() Foo {
  return &foo{}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM