👨‍💻
Dokumentasi Golang (PT Phincon)
  • 🚀Dokumentasi Bootcamp (PT Phincon)
  • Command di Golang
  • Static Type di Golang
  • Variable and Constant
    • Variable daI Constant
    • Deklarasi Variabel
    • Iota (Auto Increment)
    • Blank Identifier (Variable Underscore)
    • Access Modifier (Public or Private)
  • Tipe Data Primitif
    • Integer dan Unsigned Integer
    • Float dan Complex
    • String
    • Boolean
  • Tipe Data Aggregate
    • Array
    • Struct
  • Tipe Data Reference
    • Slice
    • Map
    • Function in Golang
      • Function
      • Function vs Method
      • Function vs Procedure
      • Private vs Public Function
      • Function Init dan Main
      • Function dengan Return Multiple Value
      • Variadic Function
      • Function sebagai Parameter
      • Anonymous Function
      • Input Function dari CLI
      • Exercise (Function)
  • Default Value setiap Tipe Data
  • Type Declaration di Golang
    • Type Declaration
    • Type Declaration Built-In di Golang
  • Kebab Case, Camel Case, Snake Case & Pascal Case di Golang
  • Konversi Tipe Data
  • If-Else dan Switch
    • If Else
    • Switch
    • Exercise
  • Looping
    • Looping For
    • Looping for range
    • Infinite Looping
    • Penerapan Looping pada Sorting
  • Operator di Golang
    • Arithmetic Operator
    • Assignment Operator
    • Relational Operator
    • Logic Operator
  • Interface
  • Interface Kosong atau Any
  • Nil
  • Pointer
    • Pass By Value dan Pass By Reference
    • Pointer (Pass By Reference)
    • Operator Address (& dan *)
    • Default Value Pointer
    • Tricky Case
    • Pointer pada Parameter di Function
    • Pointer pada Method
  • Package
    • Fmt
    • Rand
    • Os
    • Strings
      • To Lower
      • Contains
      • Split
      • Trim
      • Atoi
      • Itoa
      • EqualFold
    • Random Generator
    • Time
      • Get Current Time By Location
      • Time Sleep
      • Time Since
      • Timer & After
      • AfterFunc
      • Ticker & Tick
  • Go dan JSON
    • JSON vs XML
    • Unmarshal vs Marshal
    • Marshal (Go Object -> JSON)
    • Unmarshal (JSON -> Go Object)
    • Streaming Decoder & Encoder
    • Tag
    • JSON Go Return Byte
  • Go dan CSV
    • Insert Data ke File CSV
    • Insert 1.000.000 Data ke File CSV
  • Goroutine
    • Concurrency vs Parrarel
    • Go Routine Sederhana
    • Go Routine vs Synchronous
    • Wait Group
    • Defer
    • Channel
    • Buffered Channel
    • Select Channel
    • Deadlock - All goroutines are asleep
    • Race Condition
    • Mutex (Mutual Exclusion)
    • RW Mutex vs Mutex
    • Once
    • Pool
    • Atomic
    • Go Max Procs
    • Exit
    • Exercise 1 : Go Routine + Context + Channel
    • Exercise 2 : Worker (Go Routine + Channel + Context)
    • Exercise 3 : Random Worker (Go Routine + Channel + Context)
    • Exercise : Implementasi Goroutine dan Channel pada File CSV
  • Go Context
    • Pengenalan Context
    • Context Background & TODO
    • Context With Value
    • Context WithDeadline dan Context WithTimeout
    • Context WithCancel dan Context Done
  • Pengenalan HTTP
  • Go Native HTTP
    • HTTP Server
    • HTTP Server Multi Handler
    • HTTP Server dengan Serve Mux
    • HTTP Response Writer
    • HTTP Test
    • Routing
    • Konsep Middleware
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
    • Hit Endpoint dengan Curl di Terminal
  • Go Gin Framework
    • HTTP Server
    • Router
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
  • Golang dan Database
    • Instalasi MySQL dengan Docker Desktop
    • Instalasi PostgreSQL dengan Docker
    • Basic SQL
    • SQL Join
    • SQL Relation
    • Golang Database Driver
    • Golang dan SQL
  • Go Unit Test
    • Method di Package Testing
    • Package Assert & Require
    • Running Sub Test
    • Table Test
    • Generate Coverage Unit Testing dalam Bentuk HTML
  • Sonar Qube dan Sonar Scanner
  • Logging
  • Golang dan Redis
  • Golang dan RabbitMQ
    • Instalasi RabbitMQ dengan Docker
    • Instalasi Package RabbitMQ di Golang
    • Publisher dan Consumer
    • Publisher dan Multi Consumer
    • Setting RabbitMQ (Durable, Auto Delete dan Ack)
  • Git Command
  • Git Clone dengan SSH
  • Anotasi dan Package di Java Spring Boot
Powered by GitBook
On this page
  • 1. Switch dengan Single Case Value
  • 2. Switch Case dengan fallthrough
  • 3. Switch dengan Multiple Case
  • 4. Switch tanpa Expression
  • 5. Switch dengan Optional Statement
  • 6. Type Switch
  • Contoh code
  1. If-Else dan Switch

Switch

Switch merupakan salah satu bentuk percabangan di golang. Switch memiliki sekitar 5 bentuk seperti yang tertera dibawah ini.

1. Switch dengan Single Case Value

Switch jenis ini hanya memiliki satu value untuk setiap case. Nama variabel setelah switch bisa diberi atau tidak diberi kurung (...).

package main

import (
    "fmt"
)

func choose(value int) {
	switch value {
	case 1:
		fmt.Println(1)
	case 2:
		fmt.Println(2)
	case 3:
		fmt.Println(3)
	}
}

func main() {
	choose(1)
	choose(2)
}
1
2

2. Switch Case dengan fallthrough

Statement fallthrough digunakan untuk menampilkan case yang terpenuhi value-nya dan case setelahnya.

package main
import "fmt"

func main() {
  dayOfWeek := 5

  switch dayOfWeek {
    case 1:
      fmt.Println("Sunday")
      fallthrough
    case 2:
      fmt.Println("Monday")
      fallthrough
    case 3:
      fmt.Println("Tuesday")
      fallthrough
    case 4:
      fmt.Println("Wednesday")
      fallthrough
    case 5:
      fmt.Println("Thursday")
      fallthrough
    case 6:
      fmt.Println("Friday")
      fallthrough
    case 7:
      fmt.Println("Saturday")
      fallthrough
    default:
      fmt.Println("Invalid day")
      // fallthrough // -> cannot fallthrough final case in switch
  }
}
Thursday
Friday
Saturday
Invalid day

3. Switch dengan Multiple Case

Switch jenis ini memiliki beberapa value untuk setiap case-nya.

package main
import "fmt"

func main() {
    day := "Monday"
    
    switch day {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
        fmt.Println("Work Day")
    case "Saturday", "Sunday":
        fmt.Println("Weekend")
    }
}
Work Day

4. Switch tanpa Expression

Switch jenis ini bisa digunakan dengan relational operator (>, <, >=, <=, ==, &&, atau !=).

package main
import "fmt"

func main() {
    day := "Monday"
    
    switch {
    case day == "Monday" || day == "Tuesday" || day == "Wednesday" || day == "Thursday" || day == "Friday":
        fmt.Println("Work Day")
    case day == "Saturday" || day == "Sunday":
        fmt.Println("Weekend")
    }
}
Work Day
package main

import "fmt"

func main() {
  var isValid bool = true

  switch {
    case isValid:
      fmt.Println("true")
     default:
      fmt.Println("false")
  }
}
true
package main

import "fmt"

func main() {
  numOfDays := 28

  switch {
    case numOfDays == 28:
      fmt.Println("It's February")
    default:
      fmt.Println("Not February")
  }
}
It's February

5. Switch dengan Optional Statement

Deklarasi variabel pada switch jenis ini terletak setelah statement switch.

package main

import "fmt"

func main() {
    switch  day := "Monday"; day {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
        fmt.Println("Work Day")
    case "Saturday", "Sunday":
        fmt.Println("Weekend")
    }
}
Work Day
package main

import "fmt"

func main() {
  switch isValid := false; isValid {
    case isValid:
      fmt.Println("true")
     default:
      fmt.Println("false")
  }
}
true
package main

import "fmt"

func main() {
  switch numOfDays := 28; numOfDays {
    case 28:
      fmt.Println("It's February")
    default:
      fmt.Println("Not February")
  }
}
It's February

6. Type Switch

Type switch digunakan untuk memperoleh tipe data dari suatu nilai dalam interface kosong. Type switch memiliki format seperti di bawah ini. Banyaknya case dapat disesuaikan sesuai kebutuhan.

switch v := i.(type) {
case int:
    // program
case string:
    // program
case float64:
    // program
case bool:
    // program
case []string:
    // program
default:
    // program
}

Contoh code

package main

import "fmt"

func main() {
    var user any = []string{"member_01", "member_02", "member_03"}
    arr := user.([]string)

    switch result := user.(type) {
    case string:
        fmt.Printf("String", result)
    case int:
        fmt.Printf("Integer", result)
    case []string:
        for _, v := range arr { // cannot range over user (variable of type any)
            fmt.Print(v)
        }
    }
}
member_01
member_02
member_03

Reference:

PreviousIf ElseNextExercise

Last updated 1 year ago

LogoGo switch case (With Examples)
LogoHow To Write Switch Statements in Go | DigitalOcean
LogoA Tour of Go