Go Language for Java Developers Part 5
Part 5 of a 5 part series that explains the Go language to Java developers.
Join the DZone community and get the full member experience.
Join For FreeA variable is a storage location that holds a value. The set of permissible values is determined by the variable's type.
Primitive type variable:
int a
String b
float c
Animal a = new Animal()
Student s = new Student()
private int a
public String b
protected float c
private Animal a
Variable Naming
- Variable names are case-sensitive
- An unlimited-length sequence of Unicode letters and digits
- Beginning with a letter, the dollar sign "$", or the underscore character "_".
- No special characters allowd as identifier of variable
- We can't use reserved keywords
package main
import "fmt"
func main() {
var x int // Line 1
x = 10 // Line 2
var y string = "Hello Go!" // Line 3
fmt.Println(x)
fmt.Println(y)
}
In Line 1, var indicate it's a variable, x is the name of variable and int is the type of variable.
Since creating a new variable with a starting value is so common Go also supports a shorter statement:
y := "Hello Go!"
With the above shorter syntax Go compiler will automatically identify that y is a variable of type string and its value is "Hello Go!".
Declare multiple variable at same time:
var (
name string
age int
location string
)
- Inside Function
- Out Side Function.
Function / Local Variable
package main
import "fmt"
func main(){
var x int = 10
fmt.Println(x)
}
Global Variable
package main
import "fmt"
func main(){
var x int = 10
fmt.Println(x)
}
Any function can access the y variable, while x is local variable only accessible inside the main function.
package main
import "fmt"
var y int =10
func main(){
var x int = 10
fmt.Println(x)
fmt.Println(y)
}
func hello(){
fmt.Println(y)
}
Variable Names
package main
import "fmt"
var y int =10
func main(){
var x int = 10
fmt.Println(x)
fmt.Println(y)
}
func hello(){
fmt.Println(y)
}
Name must be start with letter
Name may contain letter, number and underscore (_)
Name is character sensetive Num and num consider as two different variable
More Reading
Published at DZone with permission of Ketan Parmar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments