Home > Software engineering >  Operation applied on values of a type
Operation applied on values of a type

Time:12-25

As mentioned in GoLang spec:

"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,

Does 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
}

CodePudding user response:

"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.

CodePudding user response:

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 set of input values.

  •  Tags:  
  • go
  • Related