What does the interface function/"cast" actually do in golang?

huangapple go评论67阅读模式
英文:

What does the interface function/"cast" actually do in golang?

问题

我对golang相对较新,我正在查看的项目中有这种模式重复了几次:

package foo

type Foo interface {
    Bar() int
}

type foo struct {
}

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

func New() Foo {
    // 为什么?
    return Foo(&foo{})
}

如果我将最后一个函数中的返回语句替换为return &foo{},一切都按照我预期的正常工作...如果我理解正确的话,这是一种鸭子类型。那么使用Foo(...)函数的目的是什么?当您在一个可能具有方法的类型中包装内置类型(如int)时,使用类型作为函数似乎是有效的。我对作者的意图很好奇。如果在语言规范中有涵盖到,我找不到它。

英文:

I'm relatively new to golang, and the project I'm looking at has this sort of pattern repeated several times:

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. So what is the point of using the Foo(...) function? 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. I'm curious as to the author's intent here. If it's covered in the language spec I was unable to find it.

答案1

得分: 3

表达式Foo(x)是一个转换。这里不需要进行转换,因为*foo可以赋值给Foo。代码应该写成:

func New() Foo {
  return &foo{}
}
英文:

The expression Foo(x) is a conversion. The conversion is not needed here because a *foo is assignable to a Foo. The code should be written as:

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

huangapple
  • 本文由 发表于 2017年1月27日 06:06:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/41883830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定