要点
go的方法
type Stu struct {
name string
age int
}
func (s *Stu)SetName(name string) {
s.name = name
}
func (s *Stu)SetAge(age int) int {
s.age = age
return age
}
func main() {
var s Stu
s.SetName("ss")
s.SetAge(11)
fmt.Println(s)
}
func (n MyInt)plusNoPtr() {
n++
fmt.Printf("PlusNoPtr: %p \n", &n)
}
func (n *MyInt)plusPtr() {
*n++
fmt.Printf("Plusptr: %p \n", n)
}
func (n *MyInt)Show() {
fmt.Printf("Num = %d", *n)
}
func main(){
var num02 MyInt = 1
num02.plusNoPtr()
fmt.Printf("PlusNoPtr后: %p, %d \n",&num02, num02)
num02.plusPtr()
fmt.Printf("PlusPtr后: %p, %d \n",&num02, num02)
}
- *与非*的自我推导
go的自我推导, MyInt 和 MyInt* 都可以调用 (MyInt)方法 和 (*MyInt)方法
func main(){
var num03 *MyInt = new(MyInt)
*num03 = 1
num03.plusNoPtr()
num03.plusPtr()
fmt.Println(*num03)
}
type myMath struct {
MyInt
}
func main(){
mm := myMath{
MyInt(1),
}
mm.Show()
}
- interface
如果使用接口,那接口的声明要全部实现,而且参数返回值必须完全一致
type myInterface interface {
InFunc()
Test() string
}
type myInt int
func (n myInt)InFunc() {
fmt.Println("MyInt InFunc")
}
func (n myInt)Test()string {
fmt.Printf("MyInt string \n")
return ""
}
func (n myInt)Test02() {
}
type myStruct struct {
}
func (m myStruct)InFunc() {
fmt.Println("MyStruct InFunc")
}
func (m myStruct)Test()string {
fmt.Printf("MyStruct string \n")
return ""
}
func Display(mi myInterface) {
mi.InFunc()
mi.Test()
}
func main() {
var a myInt
Display(a)
var b myStruct
Display(b)
}
type hand interface {
grab()
}
type human interface {
hand
eat()
}
type myInt int
func (n myInt)grab() {
}
func (n myInt)eat() {
}
func main() {
var h human
lh := myInt(1)
h = lh
h.grab()
h.eat()
var hh hand
hh = h
hh.grab()
}
m := make(map[interface{}]interface{})
m[1] = "a"
m["2"] = 1
stu := student{
"aaa",
120,
}
m[stu] = stu
fmt.Println(m)
type student struct {
name string
age int
}
func main() {
var a interface{}
a = "2"
a = 1
fmt.Println(a)
b := 10
a = b
a = 20
b,ok := a.(int)
fmt.Println(b, ok)
}