调用类型函数时没有指定类型

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

Calling type function withouth a type

问题

我创建了一个特定类型的函数。一旦我创建了它,我可以按照预期的方式调用它,但问题是当我想在不声明函数类型的变量的情况下调用它时。

下面是一个可以澄清一切的示例:

type MyStruct struct{
   number1  int
   number2  int
}

func (input *MyStruct) declareValues(val1 int, val2 int){
   input.number1 = val1
   input.number2 = val2
}

func (input MyStruct) add() int{
   return input.number1 + input.number2
}

var declared MyStruct
declared.declareValues(2,3)
fmt.Println(declared.add())   // 应该返回 5

fmt.Println(MyStruct{}.add()) // 如果成功,应该返回 0

问题是,如果我想使用更复杂的方法,并且它应该根据结构体字段是否为默认值给出不同的返回结果(因此我不需要声明变量,可以使用已声明的类型进行调用)。我必须以这种方式做,因为我不想声明一个变量来调用该方法。

英文:

I have created a function of a certain type. Once I did it, I can call it the way it's meant to be done, the problem comes when I want to call it without declaring a variable of the type of the function.

Here's an example that may clarify everything:

type MyStruct struct{
   number1  int
   number2  int
}

func (input *MyStruct) declareValues(val1 int, val2 int){
   input.number1 = val1
   input.number2 = val2
}

func (input MyStruct) add() int{
   return number1 + number2
}

var declared MyStruct
declared.declareValues(2,3)
fmt.Println(declared.add())   // Should return 5

fmt.Println(¿MyStruct?.add()) // If works, should return 0

The point is that If I want to do it with a more complex method, and it should give me an answer if the fields of the struct are the default ones (so I shouldn't have to declare a variable and I could call it using the type declared) and another return if the fields are changed.
I have to do it that way because I dont want to declare a variable to call the method.

答案1

得分: 0

你可以使用MyStruct{}.add(),在playground上试一试。这仍然会分配一个方法接收器的实例,但至少你不需要将其存储在一个单独的变量中。

英文:

You can do MyStruct{}.add(), try it on playground. This still allocates an instance of the method's receiver but at least you don't have to store it in a separate variable.

huangapple
  • 本文由 发表于 2021年12月17日 00:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/70382111.html
匿名

发表评论

匿名网友

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

确定