GO语言method

方法就相当于类的行为,对应于固定的结构体

package main

import "fmt"

type A struct{
   Name string 
} 

type B struct{
   Name string 
} 

func (a A)Print(){
  fmt.Println("A")
}
func (b B)Print(){
  fmt.Println("B")
}


func main(){
  a:=A{}
  a.Print()//achieve the method of struct A

  b:=B{}
  b.Print()//thougth the name is same it will not make trouble
}

通过a.Print和b.Print那么就是针对不同类型的所以可以分辨
但是如果加一个

func (b B)Print(int){
  fmt.Println("B")
}

因为没有重载功能它并不能够区分应该使用那么一个函数
要在receiver中改变值也应该使用指针

试试看类型别名能否添加method

package main

import "fmt"

type TZ int

func (a *TZ)Print(){
  fmt.Println("A")
}


func main(){
  var a TZ//though the bottom of the TZ is int we still can  append method
  a.Print()
}

这更加证明了虽然是别名但是到底还是不同,因为内置类型如int等就无法添加方法
方法只能对当前包的类型进行绑定

method-value和method-expression

package main

import "fmt"

type TZ int

func (a *TZ)Print(){
  fmt.Println("A")
}


func main(){
  var a TZ
  a.Print()//method value
  (*TZ).Print(&a)//method expression
}

方法的权限问题

package main

import "fmt"

type A struct{
  name string//private if 'n' public if 'N'
} 
//private and public is for package only the Name can be used in other package 
func (a *A)Print(){
  a.name="123"
  fmt.Println(a.name)
}


func main(){
  a:=A{}
  a.Print()
  fmt.Println(a.name)
}

声明:
m map[interface{}]bool
选择类型为interface{}是有原因的,因为这样可以保证元素可以是任何类型的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值