应用于类型值的操作

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

Operation applied on values of a type

问题

根据Go语言规范中的说明:

“类型确定了一组值以及与这些值相关的操作和方法。”


要在类型的值上引入一个操作或方法,

这个操作应该在从同一组中取出的值上产生结果(或值)吗?

例如,在下面的代码中,findName() 不应该是 user 类型的方法。相反,findName() 应该是一个辅助函数。

type user struct {
    name  string
    email string
    age   int
}

func (u user) findElder(other user) user {
    if u.age >= other.age {
        return u
    }

    return other
}

func (u user) findName() string {
    return u.name
}
英文:

As mentioned in Go specification:

"A type determines a set of values together with operations and methods specific to those values."


To introduce an operation or method to be applied on the values of a type,

Is that operation applied on values (taken from a set) supposed to give the result (or value) from the same set?

For example, in the below code, findName() is not supposed to be a method on type user. Instead findName() should be a helper function.

type user struct {
    name  string
    email string
    age   int
}

func (u user) findElder(other user) user {
    if u.age >= other.age {
        return u
    }

    return other
}

func (u user) findName() string {
    return u.name
}

答案1

得分: 2

“operations and methods specific to those values”并不意味着它们只适用于这些值,或者会产生这些值。

根据谷歌的解释,“specific”意味着“明确定义或确定”。在Go规范中,这里的“specific”一词是指Go是强类型的,这意味着操作和方法适用于它们所定义或确定的类型。

例如,== 运算符被指定为适用于整数类型,因此,== 运算符是特定于 intint32uint8 等值的。

英文:

"operations and methods specific to those values" does not mean that they are unique to those values, or that they result in those values.

According to Google, "specific" means "clearly defined or identified." In this quote from the Go spec, the word "specific" is used with regard to the fact that Go is strongly typed, meaning that operations and methods work on the types that they are defined or identified to work on.

For example, the == operator is specified to work on integer types, thus, the == operator is specific to values of int, int32, uint8, etc.

答案2

得分: 0

不,我认为对于从集合中取出的值应用的操作并不一定只能给出来自同一集合的结果(或值)。它们也可以来自不同的值集合。这完全取决于使用情况、类型设计和操作。

所以在你的情况下,findName() 可以很好地是一个方法,即使它返回的内容不在输入值的集合中。

英文:

No, I don't think that the operation applied on values (taken from a set) are supposed to give the result (or value), only from the same set. They can be from a different set of values as well. It all depends on the use case, the design of the type and the operation.

So in your case, findName() can very well be a method even though it is returning something not in the set of input values.

huangapple
  • 本文由 发表于 2022年12月25日 15:33:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/74912057.html
匿名

发表评论

匿名网友

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

确定