Function

  1. Return multiple output

package main

import "fmt"

func greeting() (string, string) {
   return "hi", "there"
}

func main() {
   fmt.Println(greeting())

}
  1. Looping

package main
import "fmt"
func main() {
    sum := 0
    for i := 0; i < 10; i++ {
        sum += i
    }
    fmt.Println(sum)
}
  1. Swap function

package main

import "fmt"

func main() {
   fmt.Println(swap())
}

func swap() []int {
   a, b := 15, 10
   b, a = a, b
   return []int{a, b}
}
  1. Check If Slice is Empty

package main

import "fmt"

func main() {
  arr := []int{1, 2, 3}

  if len(arr) == 0 {
    fmt.Println("Empty array")
  } else {
    fmt.Println("Not an empty array")
  }
}
  1. Reversing an Array

package main

import "fmt"

func main() {

    s := []int{1, 2, 3, 4, 5, 6}
    fmt.Println(len(s)/2)

    for i:=0; i< len(s)/2 ;i++ {
        j := len(s) - (i + 1)
        fmt.Println(j)
        s[i], s[j] = s[j], s[i]
        // 1, 2, 3, 4, 5, 6, 7
        // 7, 2, 3, 4, 5, 6, 1
        // 7, 6, 3, 4, 5, 2, 1
        // 7, 6, 5, 4, 3, 2, 1
    }

    fmt.Println(s)
}
  1. Find Duplicate Integer in Slice

package main

import "fmt"

func main() {

    s := []int{1, 2, 3, 4, 5, 5}

    for i, _ := range s {
        for j, _ := range s {
            if i != j && s[i] == s[j] {
                fmt.Println(s[i])
            }
        }
    }
}

Last updated