Home > Software design >  Calling type function withouth a type
Calling type function withouth a type

Time:12-17

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.

CodePudding user response:

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.

  • Related