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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题