This question already has an answer here:
Import everything from a package
(1 answer)
Closed 3 years ago.
Is there a way to use the names in a golang import without specifying the package name each time?
In C++ I can "use" a nampespace.
In Java, when I import something, the namespace is automatically used.
Sometimes I have a high level helper library, who's main purpose is using another pacakge, and providing some high level wrappers for it. It seems overly verbose to keep using the pacakge name over and over in the code.
package myhighlevellibrary
import "mypackage"
func Foo() *mypackage.SomeType{
a:=mypackage.Somefunction();
b:=mypackage.SomeFactoryMethod(a);
return b
}
Can I somehow avoid writing the "mypackage" literal so many times in my code? It gets much worse as my library grows larger...
This is possible using the "dot" import. Use the . as the package name in the import declaration, and so you can refer to the package's exported identifiers as if they would have been declared in the package you import them.
Quoting from Spec: Import declarations:
If an explicit period (.) appears instead of a name, all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier.
This is how your example would look like:
package myhighlevellibrary
import . "mypackage"
func Foo() *SomeType {
a := Somefunction()
b := SomeFactoryMethod(a)
return b
}
Here's a runnable Playground example:
package main
import (
. "fmt"
. "reflect"
)
func main() {
Println(TypeOf("text")) // short for: fmt.Println(reflect.TypeOf("text"))
}
See related / possible duplicate: What's C++'s `using` equivalent in golang
Related
This question already has answers here:
Go: what determines the iteration order for map keys?
(4 answers)
Closed 11 months ago.
I am a beginner programmer and was going through some GitHub repositories and found this simple classic fizzbuzz implementation using a map. However when I run it a couple of times it prints buzzfizz when the isMultiple is true for both 3 and 5. For instance, once in a while for the values 15 or 60 it may print buzzfizz instead of fizzbuzz which seems inconsistent to me and got me curious to fix it. Can someone explain why does this happen and what I am missing here? Is it merely a language behavior or the code can be improved for this consistency?
package main
import (
"fmt"
)
func isMultiple(i,j int)bool {
return i%j==0
}
func main(){
fizzbuzz:=make(map[int]string)
fizzbuzz[3]="fizz"
fizzbuzz[5]="buzz"
for i:=1; i<101; i++ {
str:=""
for k,v:=range fizzbuzz{
if isMultiple(i,k)==true{str+=v}
}
fmt.Println(i,":",str)
}
}
Edit: Decided to put the code here seeing the common convention it is better here.
Go maps are unordered data structures, you should not rely on ordering of keys.
To prevent developers from accidentally relying on small map ordering, Go randomizes small maps every time.
Please read up on maps in Go.
I have a very simple project. It is Command Line Tool written on Swift 3.0 using Xcode 8.0. This program is:
import Foundation
func aaa() {
print(a)
}
let a = "a"
aaa()
This is working perfectly well and printing "a" in console, but lets do this program more complex:
import Foundation
func aaa() {
print(a)
print(b)
}
let a = "a"
let b = "b"
aaa()
And line
print(b)
is marked with error
Use of unresolved identifier 'b'
We can make even easier:
import Foundation
func aaa() {
print(a)
}
aaa()
let a = "a"
And again, line
print(a)
is marked with error
Use of unresolved identifier 'a'
I am not newbie and I undertand that I can easily fix this error like putting all variables in the beginning of the program. Question is: why is it happening?
I thought each file with extension .swift, it is a class and I can put variable and functions, call functions in any order (all variables and constants would be global)... And one last thing, I don't have ability to test this on Swift 2.2, but I don't remember I faced this bug before, so can it be a error of Swift 3.0 compiler?
Thank you for any answer!
It appears to be a Swift compiler error:
When I tested it with other variables:
It always skips first issue and complies at second variable, at first.
Generally, if wanted to access a variable, that's inside a function, and wanted to do any action with such a variable, it must be declared there.
I would follow this convention everywhere.
Now I'm really confused. Here is my problem (Go is new to me):
Firs file:
// main.go
package main
import "./libraries/test"
func main() {
test.foo()
}
Second file:
// test.go
package test
import "fmt"
func foo() {
fmt.Println("foo")
}
My structure looks like this:
main.go
/libraries
/test
test.go
If I compile this code I'll get this error messages:
./main.go:7: cannot refer to unexported name test.foo
./main.go:7: undefined: test.foo
If I change foo to Foo everywhere the error is gone and the program works as expected.
In Go, it's an important distinction whether a symbol's name is written in upper or lower camel case. This goes for functions, but also for types (like structs or interfaces) and also struct members.
You can read this up in the Go documentation (emphasis mine):
Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case.
This means that you cannot name functions and types arbitrarily. If you need to call this function from another module, it must be named Foo, and not foo.
I suppose that you have not read the Go docs very closely. All names which begin with capital letters are exported from their package. All names in lowercase are not exported.
https://golang.org/doc/
https://golang.org/ref/spec#Exported_identifiers
I have a struct in one package that has private fields:
package foo
type Foo struct {
x int
y *Foo
}
And another package (for example, a white-box testing package) needs access to them:
package bar
import "../foo"
func change_foo(f *Foo) {
f.y = nil
}
Is there a way to declare bar to be a sort of "friend" package or any other way to be able to access foo.Foo's private members from bar, but still keep them private for all other packages (perhaps something in unsafe)?
There is a way to read unexported members using reflect (in Go < 1.7)
func read_foo(f *Foo) {
v := reflect.ValueOf(*f)
y := v.FieldByName("y")
fmt.Println(y.Interface())
}
However, trying to use y.Set, or otherwise set the field with reflect will result in the code panicking that you're trying to set an unexported field outside the package.
In short: unexported fields should be unexported for a reason, if you need to alter them either put the thing that needs to alter it in the same package, or expose/export some safe way to alter it.
That said, in the interest of fully answering the question, you can do this (and have to do it this way in Go >= 1.7)
func change_foo(f *Foo) {
// Since structs are organized in memory order, we can advance the pointer
// by field size until we're at the desired member. For y, we advance by 8
// since it's the size of an int on a 64-bit machine and the int "x" is first
// in the representation of Foo.
//
// If you wanted to alter x, you wouldn't advance the pointer at all, and simply
// would need to convert ptrTof to the type (*int)
ptrTof := unsafe.Pointer(f)
ptrTof = unsafe.Pointer(uintptr(ptrTof) + uintptr(8)) // Or 4, if this is 32-bit
ptrToy := (**Foo)(ptrTof)
*ptrToy = nil // or *ptrToy = &Foo{} or whatever you want
}
This is a really, really bad idea. It's not portable, if int ever changes in size it will fail, if you ever rearrange the order of the fields in Foo, change their types, or their sizes, or add new fields before the pre-existing ones this function will merrily change the new representation to random gibberish data without telling you. I also think it might break garbage collection for this block.
Please, if you need to alter a field from outside the package either write the functionality to change it from within the package or export it.
Edit2: Since you mention White Box testing, note that if you name a file in your directory <whatever>_test.go it won't compile unless you use go test, so if you want to do white box testing, at the top declare package <yourpackage> which will give you access to unexported fields, and if you want to do black box testing then you use package <yourpackage>_test.
If you need to white box test two packages at the same time, however, I think you may be stuck and may need to rethink your design.
I assume what you're testing is a package functionality that changes the state of that package's object, but you want to verify the internals post that change to affirm the new state is correct.
What might help would be writing Get and Set function for the private fields, so they can be accessed beyond the package scope.
package foo
type Foo struct {
x int
y *Foo
}
func (f *Foo) GetY() *Foo {
return f.y
}
func (f *Foo) SetY(newY *Foo) {
f.y = newY
}
Note that the idea of these Get and Set is to limit read and/or write access to the fields, while directly exporting them gives them read+write access automatically always. A subtle difference but worth consideration if the true goal is to only read the private fields and not operate on them (which the package internals would do in there own way)
Finally, if you're not comfortable with adding these type of wrappers for all the private fields in your package, then you can write them in a new file within that package and use build tags to ignore it in your regular builds, and include it in your test builds (wherever/however you trigger your testing).
// +build whitebox
// Get() and Set() function
go test --tags=whitebox
Regular builds ignore building test files along with them, so these wont come in your final binary. If this package is used elsewhere in entirely different ecosystem, then this file wouldn't be built still because of the build tags constraint.
I am just starting out with C++ -> Go porting and I ran across a pair of classes that were friends with each other. I am pretty sure if they are part of the same package they are friends by default, effectively.
The upper case first letter for an identifier is bound within the package. Thus they can be in separate files so long as they are in the same directory, and will have the ability to see each other's unexported fields.
Using reflect, even if it is Go stdlib, is something you should think always carefully about. It adds a lot of runtime overhead. The solution would be basically copy&paste if the two struct types you want to be friends, they simply must be in the same folder. Otherwise you have to export them. (Personally I think the woo woo about the 'risk' of exporting sensitive data is quite overblown, although if you are writing a solitary library that has no executable, maybe there can be some sense to this since users of the library will not see these fields in the GoDoc and thus not think they can depend on their existence).
Internal fields are in principle not exported from a package, which allows the author of a package to freely modify its internals without breaking any other package. Working around this using reflect or unsafe is not a good idea.
The language does deliberately not help you achieve what you want, so you're going to have to do it yourself. The simplest one is to simply merge the two packages — this is what Go unit tests typically do.
The alternative is to create an extra accessor that is only used by the bar package:
// SetYPrivate sets the value of y. This function is private to foo and bar,
// and should not be used by other packages. It might go away in future releases.
func (foo *Foo) SetYPrivate(y int) {
foo.y = y
}
An example of this technique is the runtime.MemStats function in the standard library, which returns a bunch of privates of the GC implementation.
There are multiple "hacks" to get there. One is using go:linkname. Another solution would be to have a public setter and inspect the stack trace.
I am new to type safe, and can't figure out how to do following
package main
func test(){
print("In Test")
}
func main(){
a := "test"
a()
}
You might get better answers if you state what you're trying to achieve, as reflection is usually not the best way. But reflect will help if the functions are methods on a type (net/rpc is an example of this).
package main
import (
"fmt"
"reflect"
)
type T struct {}
func (T) Add(x, y int) int {
return x + y
}
func main() {
t := reflect.ValueOf(T{})
m := t.MethodByName("Add")
args := []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)}
fmt.Println(m.Call(args)[0].Int())
}
If you were wondering how tools like godoc work, they parse the source rather than use reflection.
Edit: Playground version
A function can not be resolved from a string. However, you can assign a function to a variable.
a := test
a()
You can also put functions (assuming they all have the same signature) into a map:
var func_map := map[string]func() {
"test": test,
}
a := func_map["test"]
a()
Response to first comment by OP (too long to make another comment):
A function is not a "literal". "Literal" has a separate meaning.
Second, Go's runtime reflection does not have a lookup table mapping strings to functions. Even if it did, functions are not linked into the binary unless linked to by other code. Code only called in this method would not be in the binary.
Third, making a mapping manually is not that hard. It provides compile time type safety checks as well as security.
This is not something you should be doing in any language. It is like eval(), you really should not use it because it can be incredibly dangerous and cause unpredictable things to happen.
They don't all have the same signature
If they don't all have the same signature, how do you plan to call them? You could use the reflect package, but that is normally an indication that you are doing something wrong.
This is not a dynamic language and some things can not be done in Go. Although, they are mostly things you should not do in most languages anyways.
There's no way to dynamically look up a function by name, but I think it's worth mentioning why. Basically, the reason is so that the compiler and/or linker can eliminate unused functions.
Consider that if you were able to get a function by name, then every function in every imported package (recursively) would have to be linked into the final executable, even if it was never used, just in case someone wanted to look it up by name. People already complain about the large size of Go binaries, but this would cause them to be much larger still.