What\'s C++\'s using some_namespace::object
equivalent in golang?
According to the question here
I can get using namespace common
with sta
The following code comes close in terms of readability, but is less efficient, since the compiler cannot inline function calls anymore.
import (
"fmt"
"strings"
)
var (
Sprintf = fmt.Sprintf
HasPrefix = strings.HasPrefix
)
And, it has the side-effect of importing the names fmt
and strings
into the file scope, which is something that C++'s using
does not do.
Perhaps you could rename the package:
import (
c "common"
cout2 "github.com/one/cout"
cout2 "github.com/two/cout"
)
Then you would only have to type c.Platform
There is currently no such functionality in Go.
That's not to say it will never be added: there is open proposal to add "Alias declarations" to the language.
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()
.