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

报告相同问题?