dqg17080 2015-04-27 09:20 采纳率: 0%
浏览 49
已采纳

何时在Go中的变量名中使用前划线

Is there any special purpose of leading _ in a variable's name?

Example: func (_m *MockTracker)...

from here.

  • 写回答

2条回答 默认 最新

  • dongqu7778 2015-04-27 10:10
    关注

    There is no special meaning defined for a leading underscore in an identifier name in the spec:

    Identifiers

    Identifiers name program entities such as variables and types. An identifier is a sequence of one or more letters and digits. The first character in an identifier must be a letter.

    identifier = letter { letter | unicode_digit } .

    a
    _x9 
    ThisVariableIsExported 
    αβ
    

    Your sample is generated code from mockgen.go.

    In the package you linked you'll see things like:

    // Recorder for MockTracker (not exported)
    type _MockTrackerRecorder struct {
        mock *MockTracker
    }
    

    The sanitize function in the mockgen package prepends an underscore to package names and it seems that it's otherwise used for consistency and to ensure that identifier names remain private (i.e. not exported because they start with a capital letter). But it's not something that is defined in the Go spec.

    // sanitize cleans up a string to make a suitable package name.
    func sanitize(s string) string {
        t := ""
        for _, r := range s {
            if t == "" {
                if unicode.IsLetter(r) || r == '_' {
                    t += string(r)
                    continue
                }
            } else {
                if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
                    t += string(r)
                    continue
                }
            }
            t += "_"
        }
        if t == "_" {
            t = "x"
        }
        return t
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接