DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

裸函数作为指针不是什么新鲜事,其它的语言也是可以的,golang当然也可以,譬如

type FT func(int)
func Fa(int){}
func Test(FT){}

Test(Fa) //pass function as parameter

但是像下面这样,对象实例的方法是否可以作为函数参数传递呢?

type A struct {
   // ...
}

func (a *A) Foo(bar, baz int) {}

b := new(A)
foob := b.Foo  // foob is of type func(int, int)

答案是肯定的,而且很智能:
当特定对象实例的method作为函数指针时传递时,接受者会保证在调用的时候,调用到是这个对象实例的method,method的任何操作都会针对该对象实例生效,而且不需要传任何类似于this、self指针之类的东西

换句话说,对象实例+method 作为绑定的整体传递给接受者的

通过以下代码可以验证

package main

import (
    "fmt"
)


type Outer struct{
    a string
}

func (o *Outer)Hello(in *Inner){
   fmt.Println("Inner:",in,"\tcall\tOuter:",o.a)
}

type Inner struct{
        a string
    cb Cb
}

type Cb func(*Inner)

func (in *Inner)Register(cb Cb){
    in.cb = cb
}

func (in *Inner)Say(){
    in.cb(in)
}


func main() {
    out1 := Outer{a:"out1 instance"}
    out2 := Outer{a:"out2 instance"}

    fmt.Println("out1 :",&out1)
    fmt.Println("out2 :",&out2) 

    in1 := Inner{a:"int1 instance"}

    in1.Register(out1.Hello)
        in1.Say()
    in1.Register(out2.Hello)
    in1.Say()

}

执行起来输出如下结果

out1 : &{out1 instance}
out2 : &{out2 instance}
Inner: &{int1 instance 0xc6be0}     call    Outer: out1 instance
Inner: &{int1 instance 0xc6be0}     call    Outer: out2 instance

参考文章
https://groups.google.com/forum/#!topic/golang-nuts/t1r6px7yGIY
https://github.com/golang/go/issues/2280

posted on   DoubleLi  阅读(519)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2018-07-04 boost::threadpool 调用类成员变量并传入参数 的方法
2018-07-04 boost之ThreadPool
2017-07-04 grpc vs2015编译
2017-07-04 使用VS2015编译grpc_1.3.1
2017-07-04 vs2015编译使用GRPC
2017-07-04 在Windows上一键编译各种版本的Protobuf
2017-07-04 windwos grpc 编译
点击右上角即可分享
微信分享提示