如何获取当前包的名称? [英] How to get name of current package in go?

查看:101
本文介绍了如何获取当前包的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在运行时获得当前包的名称?

 包主

导入fmt

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

...并且结果应该是main

<现在我使用常量:

  package main 

importfmt
const(
pkgName =main


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

但我很好奇你是否可以避免这种情况

解决方案

没有运行时反映方法或函数,它提供了您正在寻找的功能。



我能找到的最接近的是:

 包主

导入(
azul3d.org/lmath.v1
fmt
反映


类型空struct {}

func main(){
fmt.Println PkgPath())
fmt.Println(reflect.TypeOf(lmath.Vec3 {0,0,0})。PkgPath())
}

这会输出:

  main 
azul3d.org/lmath.v1

您也可以阅读第一行的文件并删除包子字符串。
(不知道这是不是最好的主意)

  package main 

import(
bufio
字节
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))
}


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

解决方案

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))
}

这篇关于如何获取当前包的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆