zoukankan      html  css  js  c++  java
  • go语言之进阶篇方法值

    1、方法值

    示例:

    package main
    
    import "fmt"
    
    type Person struct {
    	name string //名字
    	sex  byte   //性别, 字符类型
    	age  int    //年龄
    }
    
    func (p Person) SetInfoValue() {
    	fmt.Printf("SetInfoValue: %p, %v
    ", &p, p)
    }
    
    func (p *Person) SetInfoPointer() {
    	fmt.Printf("SetInfoPointer: %p, %v
    ", p, p)
    }
    
    func main() {
    	p := Person{"mike", 'm', 18}
    	fmt.Printf("main: %p, %v
    ", &p, p)
    
    	p.SetInfoPointer() //传统调用方式
    
    	//保存方式入口地址
    	pFunc := p.SetInfoPointer //这个就是方法值,调用函数时,无需再传递接收者,隐藏了接收者
    	pFunc()                   //等价于 p.SetInfoPointer()
    
    	vFunc := p.SetInfoValue
    	vFunc() //等价于 p.SetInfoValue()
    
    }
    

    执行结果:

    main: 0xc00005a400, {mike 109 18}
    SetInfoPointer: 0xc00005a400, &{mike 109 18}
    SetInfoPointer: 0xc00005a400, &{mike 109 18}
    SetInfoValue: 0xc00005a4a0, {mike 109 18}
    

      

  • 相关阅读:
    29.内置方法中之描述符
    28. 面向对象进阶之内置方法上
    Sort Colors*
    Implement Trie (Prefix Tree)
    Course Schedule
    Permutations
    Reverse Linked List
    Decode Ways
    Subsets *
    Longest Consecutive Sequence *
  • 原文地址:https://www.cnblogs.com/nulige/p/10250559.html
Copyright © 2011-2022 走看看