Now that you have your first program in Go, and you know that it is installed correctly, let’s look at modifying some code to get a more robust program.
Declaring Variables
Go is a statically typed language (i.e. it is defined when variables are created and those variables cannot change) that does not permit operations that mix numeric types. For example, you can’t add a float64
to an int
, or even an int32
to an int
. This is designed to limit bugs that might occur when porting the application to other platforms, and/or handing type conversions, etc.
Variable names follow a humpback style notation.
To declare a variable in Go, you need to use a keyword var
, then define the name of the variable, and the data type.
var age int // no defined initial value
var isReady bool = true // given an initial value
Notice that you don’t need to put a semi-colon after the expression is complete.
Go has several built in data types including:
- bool
- string
- int int8 int16 int32 int64 // signed integers
- uint uint8 uint16 uint32 uint64 uintptr // unsigned integers
- byte // alias for uint8
- rune // alias for int32
- float32 float64 // float and double in most languages
- complex64 complex128 // if you want to play with real and imaginary numbers
You can also define variables in other ways in Go. This is done to speed things up when writing your code. That is, the default type is determined by the syntax of the code written.
length := 64 // Let Go determine the data type when it is defined
var width = 16 // Let Go determine the data type when it is defined
Go, in Visual Studio Code, will let you know if you don’t use a variable. This is important as Go won’t let you run the file with variables that are not used.
Declaring Constants
Declaring a constant is similar to a variable. Except instead of a var
preceding the name, you use const
.
const Pi float32 = 3.141592
Constants in Go, generally start with a capital letter to help identify them.
Logic Conditions
Your basic logic operators exist in Go, as they do in almost any language: <, <=, >, >=, ==, !=. You also have your standard C/C++/Java/JavaScript style Boolean operators &&, ||, and !.
Conditional If Statements
To create an if statement in Go, it would look like:
if age < 16 {
isReady = false
} else {
isReady = true
}
Notice that the syntax is very similar to C/C++, however, you don’t have to use parenthesis. (But you can if you want to.)
Loops in Go
Go only has one type of loop, the for loop. However, it’s syntax can be modified to support a while style loop.
for i := 1; i < 10; i++ {
}
for ; i < 10; { // while loop
}
for i < 10 { // can omit semicolons if there's only a condition
}
for key, value := range collection {
// Code to execute for each element
}
Go Variables and Basic Structure was originally found on Access 2 Learn
2 Comments
Comments are closed.