Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Why The output is only : "Hello World". Why the func f() does not print ? The variables are available for this function. Thanks for your time.
package main
import "fmt"
var x string = "hello, World"
var y string = "hello, Joe"
func main() {
fmt.Println(x)
}
func f() {
fmt.Println(x, y)
}
The problem is quite simply that you never execute the f() function.
The variables are available for this function.
Yes, this is true, but irrelevant. It doesn't matter what is available to a function that is never executed.
If you want to execute f(), just call it:
func main() {
fmt.Println(x)
f()
}
See a working example in the playground.
Perhaps you are confused by the fact that main() (and init() when it exists) are automatically executed when a Go program starts. These two function names are special. init() functions (if they exist) are executed first, during program startup. Then main() is executed, and when main() exits, the program terminates.
All other functions must be called from within main() (or rarely init(), but avoid that unless you really know what you're doing.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
Take this example -
func funcB() { fmt.Println("Hi") })
funcA(funcB)
Is funcA receiving a pointer to funcB? Or is it receiving a full-blown immutable function?
So, if I execute this code -
func funcA() { fmt.Println("Hi") })
funcB(funcA)
funcC(funcA)
funcD(funcA)
funcE(funcA)
funcF(funcA)
are all of the function calls creating a new funcA object, or are all of them receiving the same pointer to funcA?
Functions hold no state to be passed either by value or by reference, i.e., they are just executable code. When you pass a function to another function, you are giving some reference to the executable code of the function's body.
How about anonymous functions?
You can also store an anonymous function or closure into a func() value. In this case, your question becomes more interesting because closures can hold state.
Is a closure passed to a function provided by value or by reference?
func call(f func()) {
f()
}
func main() {
var i int
f := func() {
fmt.Println(i)
i++
}
call(f)
call(f)
}
Running the code above outputs:
0
1
We can conclude that the closure's state – i.e., the captured i variable – is somehow being shared between calls to call(). In principle, this behavior could have been achieved by:
The closure captured its environment by reference and was passed either by value or by reference.
The closure captured its environment by value and was passed by reference only.
To find out how the closure captures its environment, we can change the value of i in main() and see whether the i value that the closure sees gets affected. If we append the code below to main():
i = 100
call(f)
Then, 100 is displayed. Therefore, i is shared between main() and the closure (i.e., the closure doesn't have its own copy of i). So, closures capture their environment by reference (we can now rule out the 2. option above).
At this point, we still haven't found whether a closure is passed by value or by reference. However, we already know that a closure's captured state is, in effect, passed by reference to functions because a closure holds references to the captured state. This is very likely the most critical insight.
Even so, we can see closures are passed by value:
func change(f func()) {
f = func() {
fmt.Println("replaced")
}
}
func main() {
f := func() {
fmt.Println("original")
}
change(f)
f() // prints "original"
}
Conclusion
Functions are just code. They don't store state. A function is a memory address to some executable code. When you pass a function to another function, you are giving this address.
Anonymous functions or closures can hold state that corresponds to the enclosing environment. Even though closures are passed by value, the states they hold are references to the environment they captured. So, the net effect is that the closure's captured environment is passed by reference.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have a package A in Go that looks like
package A
var Something int
func Do_something() {
Something = 100
}
where do_something in package A is called in main.go
package main
import "example.com/this_project/A"
func main() {
A.Do_something()
}
That works well, but now I add package B.
package B
import (
"example.com/this_project/A"
"fmt"
"strconv"
)
_ = do_something_else()
func do_something_else() {
fmt.Println("%s is the value of something", strconv.Itoa(A.Something))
}
func Some_other_function() {
do_whatever()
}
Some_other_function will also get called in main.go
package main
import "example.com/this_project/A"
import "example.com/this_project/B"
func main() {
A.Do_something()
B.Some_other_function()
}
When I run this program, I expect it to output
100
But instead, it outputs
0
I think this means that package B is running before main.go, so I tried using time.sleep, but it just caused the entire project to stop. Any suggestions will be appreciated.
All global variables are initialized before main starts running. Because of that, this line:
_ = do_something_else()
will run before main starts, which will print the current value of the variable, which is 0 at that point.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
How come no warnings are issued for the following code?
$ cat ret.go
package main
import "fmt"
func foobar(x int, y int) (z, w int) {
if x+y > 100 {
_,w = 3,5
} else {
_,w = "MMM",9
}
return z,w
}
func main() {
var x int
_,x = foobar(42,13)
fmt.Println(x)
}
$ go build -gcflags=-l ret.go
For the least, the go compiler should know the size of z right?
In golang, you can define multiple variable in one line like next:
var identifier1, identifier2 type
So, z, w here both declared as int.
Additional, see this:
The return values of a function can be named in Golang
Then, if you not assign a value to z, it will has a default value of int, that is 0. So, no warning, the code is ok.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm relatively new to Golang and I'm trying to wrap my head around the semantics of goroutines.
Is there a difference between:
func someFunc() {
for {
//some code handled by a persistent connection
}
}
go someFunc()
and
func someFunc() {
go func() {
for {
//some code handled by a persistent connection
}
}()
}
It's a question of what you're trying to communicate. Generally functions should represent behavior that isn't tied to the mode of operation of that behavior. If someday your code becomes all asynchronous because of some business concern, it shouldn't require touching any code inside of someFunc.
For that reason I would prefer the former to the latter, but ultimately both are spawning a goroutine and executing code on that thread. The advantage to the former is that running someFunc synchronously becomes possible.
There are other small differences as well. The first definition of someFunc is running until it finishes its behavior. Let's imagine a long-running expensiveAction is taken during someFunc, such that the definition becomes:
func someFunc() {
ok := expensiveAction()
if !ok {
panic("Something bad happened")
}
}
and
func someFunc() {
go func() {
ok := expensiveAction()
if !ok {
panic("Something bad happened")
}
}()
}
The first definition of someFunc, when called, will run until expensiveAction has finished. The second definition will define the anonymous function, spin up the goroutine and schedule its execution, then immediately exit. This could make performance testing more difficult, or even create subtle timing bugs.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a custom type named ProtectedCustomType and I don't want the variables within that to be set or get directly by the caller, rather want a Getter / Setter methods to do that.
Below is my ProtectedCustomType
package custom
import "fmt"
type ProtectedCustomType struct {
name string
age string
phoneNumber int
}
func (pct *ProtectedCustomType) SetAge (age string) {
pct.age=age
fmt.Println(pct.age)
}
func (pct *ProtectedCustomType) GetAge () string {
return pct.age
}
And here is my main function
package main
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := custom.ProtectedCustomType{}
pct.SetAge("23")
age:=pct.GetAge
print (age)
}
func main() {
structCheck2()
}
I am expecting it to print 23, but it is printing as 0x48b950
This (your code) takes the pct instance's GetAge method and stores it in a variable:
age:=pct.GetAge
This calls the GetAge method and stores its return value in a variable:
age:=pct.GetAge()
Consider taking the Tour of Go and reading the Go Specification to get a basic understanding of Go syntax.