douzhi1924 2014-08-12 11:08
浏览 981
已采纳

如何在go中获取当前包的名称?

Is there a way to get on runtime the name of current package?

package main

import "fmt"

func main() {
    pkgName := {some magic here:)}
    fmt.Println(pkgName)
}

... and the result should be "main"

Right now I'm using constant like:

package main

import "fmt"
const (
    pkgName = "main"
)

func main() {
    fmt.Println(pkgName)
}

but I'm curious if you can avoid this

  • 写回答

4条回答 默认 最新

  • doubiantiao4994 2014-08-12 11:52
    关注

    There is no runtime or reflect method or function that provides the functionality that you are looking for.

    The closest thing I could find is:

    package main
    
    import (
        "azul3d.org/lmath.v1"
        "fmt"
        "reflect"
    )
    
    type Empty struct{}
    
    func main() {
        fmt.Println(reflect.TypeOf(Empty{}).PkgPath())
        fmt.Println(reflect.TypeOf(lmath.Vec3{0, 0, 0}).PkgPath())
    }
    

    This would output:

    main
    azul3d.org/lmath.v1
    

    You could also read the first line of the file and remove the "package" substring. (Not sure if it's the best idea)

    package main
    
    import (
        "bufio"
        "bytes"
        "fmt"
        "os"
    )
    
    func main() {
        file, err := os.Open("so.go")
        if err != nil {
            panic(err)
        }
        r := bufio.NewReader(file)
        line, _, err := r.ReadLine()
        if err != nil {
            panic(err)
        }
        packageName := bytes.TrimPrefix(line, []byte("package "))
        fmt.Println(string(packageName))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo