What's C++'s `using` equivalent in golang

后端 未结 4 480
挽巷
挽巷 2021-01-18 00:47

What\'s C++\'s using some_namespace::object equivalent in golang?

According to the question here I can get using namespace common with sta

4条回答
  •  孤街浪徒
    2021-01-18 01:47

    As others said, it is not possible in Go. In Go you import packages, not functions or types from packages.

    Note that you can easily achieve what you want if you create a helper package.

    Let's say you want "using" the fmt.Println() and fmt.Printf() functions only. Create a helper package:

    package helper
    
    import "fmt"
    
    func Println(a ...interface{}) (n int, err error) {
        return fmt.Println(a...)
    }
    
    func Printf(format string, a ...interface{}) (n int, err error) {
        return fmt.Printf(format, a...)
    }
    

    And where you want the C++'s "using" functionality, import using a dot .:

    import . "helper"
    
    func Something() {
        Println("Hi")
        Printf("Using format string: %d", 3)
    }
    

    The result is that only the exported identifiers of the helper package will be in scope, nothing else from the fmt package. You can use this single helper package to make functions available from packages other than fmt of course, too. helper can import any other packages and have a "proxy" or delegator function publishing their functionality.

    Personally I don't feel the need of this. I would just import fmt and call its functions using fmt.Println() and fmt.Printf().

提交回复
热议问题