Hello, Welcome back; Today , we create new type of method receiver. When a function receive a value type parameter, on heap it will create copies of all the parameters, you pass. To avoid this problem, function receive reference type variable. Such as pointer, channels. Pointers have following advantages over variable. It Directly access, no copy , change in original value.
Method Receiver Pointer:
If you can write a code in C. Then you know, methods are not inherit C or Java Language. It's inherit from unix messages.
If you can write a code in C. Then you know, methods are not inherit C or Java Language. It's inherit from unix messages.
func (c *Cal) Sum(y int) int{ // code }
Cases :
There're following cases that are exit
1. If a method receiver and method argument both are T or *T type , it directly access.
2. If a method receiver is T type, however method argument as *T type. then it need reference to access (&)
3. If a method receiver have *T and method argument as T type then dereference (*).
package main
import (
"fmt"
)
type Cal struct{
y int
}
func(c *Cal)Sum(y int) int{
return c.y -y
}
func main() {
// case 1
rec := Cal{3}
res := rec.Sum(2)
fmt.Println(res)
// case 2
r := Cal{4}
re := &r
fmt.Println(re.Sum(2))
//case 3
rc := Cal{5}
fmt.Println((&rc).Sum(2))
}
If you want to checkout the output, goto play link. If you remember my previous article it indirectly access and then set values, but in this example you only access via through pointers and also it's good approach. I hope you enjoy and learn more. Please share with your friends. Have a great day.
Comments
Post a Comment