Learning Go - newgeekorder/TechWiki GitHub Wiki

Hello World

the ubiquitous hello world

package main
import "fmt"
// this is a comment
func main() {
 fmt.Println("Hello World")
}

Note: convention with capital "P" on Println

to compile and run

go run hello.go 

to build a binary

go build hello.go

Strings

String literals can be created using double quotes "Hello World" or back ticks `Hello World `. The difference between these is that

  • double quoted strings cannot contain newlines and they allow special escape sequences. For example \n \t etc

Common String Macros ..

Several common operations on strings include

  • finding the length of a string: len("Hello World"),

Note also Strings are arrays and can be accessed:

  • "Hello World"[1],
  • and operations are supported on Strings "Hello " + "World".
package main
import "fmt"
func main() {
 fmt.Println(len("Hello World"))
 fmt.Println("Hello World"[1])
 fmt.Println("Hello " + "World")
}

Variables And Declarations

Variables are defined with name type e.g

 var x string = "Hello World"

Declarations are introduced by a keyword (var, const, type, func) and are reversed compared to C, Java:

var i int
const PI = 22./7.
type Point struct { x, y int }
func sum(a, b int) int { return a + b }

Available types:

value value
boolean true or false
Numeric types
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
Integer
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32