不能在Golang中调用Println时删除fmt前缀 [英] Cant I get rid of fmt prefix when calling Println in Golang

查看:287
本文介绍了不能在Golang中调用Println时删除fmt前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过 http://tour.golang.org/#1

  package main 

importfmt

func main(){
Println(Hello World)
}

这会产生错误:

  prog.go:3:已导入且未使用:fmt
prog.go:6:undefined:Println
[进程退出非零状态]

程序已退出

是否意味着我有义务在Println前加上fmt包名称?在其他语言中,它不是强制性的。

解决方案

如果函数不在当前包中,



然而你可以做的是为这个包创建一个别名:

  import ffmt

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

重命名功能:

  importfmt

var Println = fmt.Println

func main(){
Println(Hello World)
}

或者使用作为别名它可能是你最想要的):

  import。 fmt

func main(){
Println(Hello World)
}

请注意,在这种情况下,别名不是空白。从Go的规格


合格的标识符是一个符合软件包名称前缀的标识符。包名和标识符都不能为空。



QualifiedIdent = PackageName。标识符。


另一个来自同一个规格

$ p $ importlib / mathmath.Sin
导入mlib / mathm.Sin
导入。 lib / mathSin


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.

解决方案

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

这篇关于不能在Golang中调用Println时删除fmt前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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