douchongbc72264 2014-07-18 10:27
浏览 135
已采纳

不能在Golang中调用Println时摆脱fmt前缀

I tried http://tour.golang.org/#1

package main

import "fmt"

func main() {
    Println("Hello World")
}

This generates error :

prog.go:3: imported and not used: "fmt"
prog.go:6: undefined: Println
 [process exited with non-zero status]

Program exited

Does it mean I am obliged to prefix Println with "fmt" package name ? In other languages it isn't mandatory.

  • 写回答

1条回答 默认 最新

  • douwengzao5790 2014-07-18 10:33
    关注

    You will have to prefix a function if it is not in the current package.

    What you can do however is create an alias for this package:

    import f "fmt"
    
    func main() {
        f.Println("Hello World")
    }
    

    Or "rename" the function:

    import "fmt"
    
    var Println = fmt.Println
    
    func main() {
        Println("Hello World")
    }
    

    Or use . as alias (it may be what you would like most):

    import . "fmt"
    
    func main() {
        Println("Hello World")
    }
    

    Note that in that case, the alias is not blank. From the specifications of Go:

    A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.

    QualifiedIdent = PackageName "." identifier .

    And another example from the same specifications:

    import   "lib/math"         math.Sin
    import m "lib/math"         m.Sin
    import . "lib/math"         Sin
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失