If I use variable inside a function then Go gives error otherwise not please check 2 examples.
GIVES ERROR n declared but not used
https://play.golang.org/p/z-EktUDkNDz
package main
func main() {
var n int
n = 10
}
NO Error when var declared outside the function https://play.golang.org/p/nFSEoktcE5e
package main
var n int
func main() {
n = 10
}
That's as per the standard:
Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.
Reference: https://golang.org/ref/spec#Variable_declarations
Please make a note that it states "may make". That means it's up to a particular compiler implementation. But in general it's better to assume it's not allowed.
And there is no such similar restriction for variables declared in a global scope.
Related
Does fmt.Println need to always belong to a function?
Have used Python before and it allows it but on research, it seems that Java doesn't
fmt.Println("can I do it?")
Returns:
syntax error: non-declaration statement outside function body
It may be outside of a function, see this example:
var n, err = fmt.Println("I can do it")
func main() {
fmt.Println("In main(),", n, err)
}
It outputs (try it on the Go Playground):
I can do it
In main(), 12 <nil>
(The output values 12 <nil> are the values returned by the first fmt.Println() call, the number of bytes it has written and the error it returned which is nil indicating no error.)
Also note that you don't even have to store the return values of fmt.Prinln(), you can use the blank identifier like this:
var _, _ = fmt.Println("I can do it")
It cannot stand on its own at the top level "between" top-level declarations, but the above variable declaration (with blank identifier) pretty much achieves the same.
Spec: Source file organization:
Each source file consists of a package clause defining the package to which it belongs, followed by a possibly empty set of import declarations that declare packages whose contents it wishes to use, followed by a possibly empty set of declarations of functions, types, variables, and constants.
SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
Obviously a package clause or import declaration can't contain an fmt.Println() call, and the top level declarations:
Declaration = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
A constant declaration cannot contain an fmt.Println() call, that's not a constant expression. A type declaration also cannot contain function calls.
A variable declaration can, as shown in the example at the top of the answer.
Function and method declarations could also call fmt.Println(), but you were asking specifically if fmt.Println() can be called outside of them.
So the only place it is allowed outside of functions that is allowed at the top level is in variable declarations.
go always starts execution in the main function, so fmt.Println() need to be in the main function or a function that is called in main.
I am going through the Go specification to learn the language, and these points are taken from the spec under Declarations and scope.
Though I am able to understand points 1-4, I am confused on points 5 and 6:
The scope of a constant or variable identifier declared inside a
function begins at the end of the ConstSpec or VarSpec (ShortVarDecl
for short variable declarations) and ends at the end of the
innermost containing block.
The scope of a type identifier declared inside a function begins at
the identifier in the TypeSpec and ends at the end of the innermost
containing block.
This is the code which I used to understand scope in Go:
package main
import "fmt"
func main() {
x := 42
fmt.Println(x)
{
fmt.Println(x)
y := "The test message"
fmt.Println(y)
}
// fmt.Println(y) // outside scope of y
}
From this what I understand is scope of x is within the main function, and the scope of y is inside the opening and closing brackets after fmt.Println(x), and I cannot use y outside of the closing brackets.
If I understand it correctly, both points 4 and 5 are saying the same thing. So my questions are:
If they are saying the same thing, what is the importance of both the
points?
If they are different, can you please let me know the difference?
They're making the same point, with the same rules, about two different things: the first is about variables and constants, the second is about type identifiers. So, if you declare a type inside a block, the same scoping rules apply as would apply to a variable declared at the same spot.
Besides applying to different things (rule #5 is for constant- and variable declarations, rule #6 is for type declarations), there is also an important difference in wording:
The scope of a constant or variable identifier declared inside a
function begins at the end of the ConstSpec or VarSpec (ShortVarDecl
for short variable declarations) and ends at the end of the
innermost containing block.
The scope of a type identifier declared inside a function begins at
the identifier in the TypeSpec and ends at the end of the innermost
containing block.
This is the reason why there are 2 rules and not one.
What does this mean? What does the difference imply?
# 5 Variable and Constant declarations (inside a function)
The scope of the declared variables or constants begins at the end of the declaration. This means if you're creating a function variable, initializing it with an anonymous function, it can't refer to itself.
This is invalid:
f := func() {
f()
}
Attempting to compile:
prog.go:5:3: undefined: f
This is because the declaration ends after the closing bracket of the anonymous function, so inside of it you can't call f(). A workaround would be:
var f func()
f = func() {
f()
}
Now here the declaration of f ends at the closing parenthesis (of its type func()), so in the next line when we assign an anonymous function to it, it is valid to refer to f (to call the function value stored in the f variable) because it is now in scope. See related question: Define a recursive function within a function in Go
Similarly, when initializing a variable e.g. with a composite literal, you can't refer to the variable inside of it:
var m = map[int]string{
1: "one",
21: "twenty-" + m[1],
}
This gives a compile-time error ("undefined: m"), because m is not in scope yet inside the composite literal.
And obviously this workaround works:
var m = map[int]string{
1: "one",
}
m[21] = "twenty-" + m[1]
# 6 Type declarations (inside a function)
The scope of the declared type begins at the identifier in the declaration. So in contrast to rule #5, it is valid to refer to the type itself inside its declaration.
Does it have any advantage / significance?
Yes, you can declare recursive types, such as this:
type Node struct {
Left, Right *Node
}
The type identifier Node is in scope right after it appears in the type declaration, which ends with the closing bracket, but before that we could refer to it, meaningfully.
Another example would be a slice type whose element type is itself:
type Foo []Foo
You can read more about it here: How can a slice contain itself?
Yet another valid example:
type M map[int]M
In Go you can initialise an empty string (in a function) in the following ways:
var a string
var b = ""
c := ""
As far as I know, each statement is semantically identical. Is one of them more idiomatic than the others?
You should choose whichever makes the code clearer. If the zero value will actually be used (e.g. when you start with an empty string and concatenate others to it), it's probably clearest to use the := form. If you are just declaring the variable, and will be assigning it a different value later, use var.
var a string
It's not immediately visible that it's the empty string for someone not really fluent in go. Some might expect it's some null/nil value.
var b = ""
Would be the most explicit, means everyone sees that it's a variable containing the empty string.
b := ""
The := assigment is so common in go that it would be the most readable in my opinion. Unless it's outside of a function body of course.
There isn't a right way to declare empty variables, but there are some things to keep in mind, like you can't use the := shortcut outside of a function body, as they can with var:
var (
name string
age int64
)
I find var name = "" to be the clearest indication that you're declaring an empty variable, but I like the type explicitness of var name string. In any case, do consider where you are declaring variables. Sometimes all at once outside the function body is appropriate, but often nearest to where you actually use it is best.
rob (Pike?) wrote on a mailthread about top-level declaration
At the top level, var (or const or type or func) is necessary: each item must be introduced by a keyword for ur-syntactic reasons related to recognizing statement boundaries. With the later changes involving semicolons, it became possible, I believe, to eliminate the need for var in some cases, but since const, type, and func must remain, it's not a compelling argument.
There is a certain ambiguity in "short-variable" declarations (using :=), as to whether the variable is declared or redeclared as outlined in the specs:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
There is absolutely no difference in the generated code (with the current compiler – Go 1.7.4), and also gometalinter does not complain for any of those. Use whichever you like.
Some differences:
You can only use the short variable declaration in functions.
With short variable declaration, you can create variables of multiple types in one line, e.g.
a, b := "", 0
The following 3 apps generate identical code:
a.go
package main
import "fmt"
func main() { var a string; fmt.Println(a) }
b.go
package main
import "fmt"
func main() { var a = ""; fmt.Println(a) }
c.go
package main
import "fmt"
func main() { a := ""; fmt.Println(a) }
To verify, build each (e.g. with go build -o a), and use diff on Linux to compare the executable binaries:
diff a b && diff a c
I try to stick to the short declaration for a couple of reasons.
It's shorter
Consistency
Allocates memory for maps, slices and pointers to structs and types.
Although var a string and a := "" are the same, b := []T{} and var b []T are not the same. When dealing with slices and maps the shorter declaration will not be nil. More often then not (especially with maps) I want allocated memory.
There are few situations where var will be needed, for instance, you are calling a function that will populate a property of a type.
var err error
foo.Name, err = getFooName()
Using := syntax in the above situation will error out since foo.Name is already declared.
just
*new(string)
It's only stuff in stackoverf related to empty strings in go. So it should be here
Can someone give me an explanation as to when and why I would use anonymous scope inside a function? (I'm not sure what it's actually called).
I've been given some legacy code to maintain and some of the functions contain this "scope" I have not seen before:
(simplified for demonstration purposes)
func DoSomething(someBoolValue bool) string {
if someBoolValue {
// do some stuff
return "yes"
}
{
// weird scope code
}
return "no"
}
I have created a Go Playground to demonstrate some actual code (that throws an error).
It is called Variable scoping and shadowing:
Go is lexically scoped using blocks:
1-The scope of a predeclared identifier is the universe block.
2-The scope of an identifier denoting a constant, type, variable, or
function (but not method) declared at top level (outside any function)
is the package block.
3-The scope of the package name of an imported
package is the file block of the file containing the import
declaration.
4-The scope of an identifier denoting a method receiver,
function parameter, or result variable is the function body.
5-The scope of a constant or variable identifier declared inside a function
begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short
variable declarations) and ends at the end of the innermost containing
block.
6-The scope of a type identifier declared inside a function
begins at the identifier in the TypeSpec and ends at the end of the
innermost containing block. An identifier declared in a block may be
redeclared in an inner block. While the identifier of the inner
declaration is in scope, it denotes the entity declared by the inner
declaration.
The package clause is not a declaration; the package name does not
appear in any scope. Its purpose is to identify the files belonging to
the same package and to specify the default package name for import
declarations.
your working sample code:
package main
import (
"fmt"
)
func main() {
i := 10
{
i := 1
fmt.Println(i) // 1
}
fmt.Println(i) // 10
}
output:
1
10
and see: Where can we use Variable Scoping and Shadowing in Go?
{} in Go form a Syntactic Block. Each block defines a new scope. These are same blocks that you use with if and for for example.
With respect to your code, I guess they exist mainly for readability purpose. You can reuse or hide variable defined in the enclosing scope to make use of variables names that maybe declare the code's intent more clearly.
Other than that they can also be used to group a bunch of related statements, again for readability.
To understand their behavior, refer to #Amd's answer.
This Go program will not compile. It throws the error global_var declared and not used
package main
import "log"
var global_var int
func main() {
global_var, new_string := returnTwoVars()
log.Println("new_string: " + new_string)
}
func returnTwoVars() (int, string) {
return 1234, "woohoo"
}
func usesGlobalVar() int {
return global_var * 2
}
However, when I remove the need for using the := operator by declaring new_string in the main function and simply using =, the compiler doesn't have a problem with seeing that global_var is declared globally and being used elsewhere in the program. My intuition tells me that it should know that global_var is declared already
The compiler doesn't complain about the global_var outside main. It only complains about the newly created global_var in main that you don't use. Which you can check by looking at the line number that go mentions.
You can try an empty program with a global_var outside any function that nobody references: no problems there. And of course, the usesGlobalVar function that does reference the actual global symbol has nothing to do with the one you create in main.