V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
solxnp

请教下反射后类型转换的问题

  •  
  •   solxnp · Aug 25, 2020 · 1818 views
    This topic created in 2083 days ago, the information mentioned may be changed or developed.
    目前有这样一个需求:
    通过配置文件,反射获取目标的方法,但最多只能通过 reflect.ValueOf.MethodByName 或者 reflect.ValueOf.Method 得到一个 reflect.Value 类型,虽然直接调用.Call()能执行此方法,但我想将 reflect.Value 类型转为 func()类型,如 f := func; f() 这样调用,而不是通过 reflect.Value.Call()调用。

    先不讨论为什么要如此放屁脱裤子多此一举,就想问问大佬们,能转成 func()类型吗
    4 replies    2020-08-25 17:33:32 +08:00
    CRVV
        1
    CRVV  
       Aug 25, 2020
    https://golang.org/pkg/reflect/#Value.Interface

    f := Value.Interface().(func())
    f()

    也许能用,我没试
    Vegetable
        2
    Vegetable  
       Aug 25, 2020
    f := v.Interface().(func() int)
    Vegetable
        3
    Vegetable  
       Aug 25, 2020
    得注意函数的类型必须包括参数和返回
    solxnp
        4
    solxnp  
    OP
       Aug 25, 2020
    @CRVV @Vegetable 多谢两位大佬,可用。原来要先转回 interface,才能再做类型转换,被自己蠢哭
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1364 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 17:23 · PVG 01:23 · LAX 10:23 · JFK 13:23
    ♥ Do have faith in what you're doing.