basic syntax
**First program in Go**
```go
package main
import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World!")
}
```
**Run the code**
```go
go build hello.app
./hello
```
```go
$ go run hello.go
Hello, World!
```
**variables**
```go
func main() {
var x float64 = 20.0
y := 42
z = "abc"
var a, b, c = 3, 4, "foo"
const LENGTH int = 10
}
```
**IF-ELSE**
```go
if( a == 10 ) {
/* if condition is true then print the following */
fmt.Printf("Value of a is 10\n" )
} else if( a == 20 ) {
/* if else if condition is true */
fmt.Printf("Value of a is 20\n" )
} else if( a == 30 ) {
/* if else if condition is true */
fmt.Printf("Value of a is 30\n" )
} else {
/* if none of the conditions is true */
fmt.Printf("None of the values is matching\n" )
}
}
```
**switch**
```go
func main() {
/* local variable definition */
var grade string = "B"
var marks int = 90
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50,60,70 : grade = "C"
default: grade = "D"
}
switch {
case grade == "A" :
fmt.Printf("Excellent!\n" )
case grade == "B", grade == "C" :
fmt.Printf("Well done\n" )
case grade == "D" :
fmt.Printf("You passed\n" )
case grade == "F":
fmt.Printf("Better try again\n" )
default:
fmt.Printf("Invalid grade\n" );
}
fmt.Printf("Your grade is %s\n", grade );
}
```
**Loop**
```go
/* for loop execution */
for a := 0; a < 10; a++ {
fmt.Printf("value of a: %d\n", a)
}
for a < b {
a++
fmt.Printf("value of a: %d\n", a)
}
for i,x:= range numbers {
fmt.Printf("value of x = %d at %d\n", x,i)
}
```
**Goto**
```go
func main() {
/* local variable definition */
var a int = 10
/* do loop execution */
LOOP: for a < 20 {
if a == 15 {
/* skip the iteration */
a = a + 1
goto LOOP
}
fmt.Printf("value of a: %d\n", a)
a++
}
}
```
**Function**
```go
/* function returning the max between two numbers */
func max(num1, num2 int) int {
/* local variable declaration */
result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Mahesh", "Kumar")
fmt.Println(a, b)
}
```
```go
func main() {
/* local variable definition */
var a int = 100
var b int = 200
fmt.Printf("Before swap, value of a : %d\n", a )
fmt.Printf("Before swap, value of b : %d\n", b )
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b)
fmt.Printf("After swap, value of a : %d\n", a )
fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* save the value at address x */
*x = *y /* put y into x */
*y = temp /* put temp into y */
}
```