douxu2467 2013-12-09 04:01
浏览 281
已采纳

是否可以知道Go中函数的返回值类型?

For example, I want to do something like this,

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var f func(int) int
    v := reflect.ValueOf(f)
    fmt.Println(v.ReturnType() == reflect.TypeOf(1)) // => true
}

ReturnType method doesn't exist in reflect package. My question is, can I implement such a function without using cgo.

  • 写回答

1条回答 默认 最新

  • douju1953 2013-12-09 04:18
    关注

    Rather than using reflect.ValueOf(f) try reflect.TypeOf(f). The Type type has two relevant methods named NumOut and Out(int). To get the types of all return values in order, you can use the following loop

    typ := reflect.TypeOf(f)
    
    for i := 0; i < typ.NumOut(); i++ {
        returnType := typ.Out(i)
        // do something with returnType
    }
    

    If you're certain your function only has one return value, you can always get it with Out(0), the standard disclaimers about making sure your input is correct apply.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 gki vendor hook
  • ¥15 centos7中sudo命令无法使用
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联