在Golang中调用Println时,我不能去掉fmt前缀吗?

huangapple go评论176阅读模式
英文:

Cant I get rid of fmt prefix when calling Println in Golang

问题

我尝试了http://tour.golang.org/#1

package main

import "fmt"

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

这个代码生成了错误:

prog.go:3: 导入的包未使用:"fmt"
prog.go:6: 未定义:Println
 [进程以非零状态退出]

程序退出

这是否意味着我必须在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

得分: 11

如果一个函数不在当前包中,你需要在函数名前加上包名作为前缀。

不过你可以为这个包创建一个别名:

import f "fmt"

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

或者将函数进行“重命名”:

import "fmt"

var Println = fmt.Println

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

或者使用.作为别名(这可能是你最喜欢的方式):

import . "fmt"

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

需要注意的是,在这种情况下,别名不能为空白。根据Go的规范

限定标识符是一个带有包名前缀的标识符。包名和标识符都不能是空白。

QualifiedIdent = PackageName "." identifier

以下是同一规范中的另一个示例:

import   "lib/math"         math.Sin
import m "lib/math"         m.Sin
import . "lib/math"         Sin
英文:

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

huangapple
  • 本文由 发表于 2014年7月18日 18:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/24822826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定