Kubernetes 이야기

Go 기본 문법 본문

개발/go

Go 기본 문법

kmaster 2022. 9. 24. 20:40
반응형

Hello World

package main
import "fmt"

func main() {
    fmt.Println("Hello!")
}

Go CLI Commands

# Compile & Run code
$ go run [file.go]# Compile
$ go build [file.go]
# Running compiled file
$ ./hello# Test packages
$ go test [folder]# Install packages/modules
$ go install [package]# List installed packages/modules
$ go list# Update packages/modules
$ go fix# Format package sources
$ go fmt# See package documentation
$ go doc [package]# Add dependencies and install
$ go get [module]# See Go environment variables
$ go env# See version
$ go version

Go Modules

# Create Module
$ go mod init [name]

Variables

var value int
value = 10
var isActive = true
text := "Hello"
var i, j, k = 1, 2, 3
var text string // ""
var boolean bool // false
const pi = 3.1415

Conditional Statements

// If / Else
i := 1
if i > 0 {
  ...
} else {
  ...
}

i := 1
if i > 0 {
  ...
} else if i > 0 && i < 2 {
  ...
} else if i > 1 && i < 4 {
  ...
} else {
  ...
}

i := 2.567

if j := int(i); j == 2 {
  ...
} else {
  ...
}

text := 'hey'
switch text {
    case 'hey':
        ...
    case 'bye':
        ...
    default:
        ...
}

value := 5
switch {
    case value < 2:
        ...
    case value >= 2 && value < 6:
        ...
    default:
        ...
}

Loops

for i := 0; i < 10; i++ {
    ...
}

i := 0;
for i < 10 {
    i++
}

for {}

Arrays

values := [5]int{1, 2, 3, 4, 5}
values[1:3] // {2, 3, 4}
values[:2] // {1, 2, 3}
values[3:] // {3, 4}
len(values) // 5
values = values[:1]
len(values) // 2
cap(values) // 5

slice := []int{ 1, 2 }
slice = append(slice, 3)
slice // { 1, 2, 3 }
slice = append(slice, 3, 2, 1)
slice // { 1, 2, 3, 3, 2, 1 }

slice := string["W", "o", "w"]
for i, value := range slice {
    i // 0, then 1, then 2
    value // "W", then "o", then "w"
}

for i := range slice {
    i // 0, then 1, then 2
}

for _, value := range slice {
   value // "W", then "o", then "w"
}

Functions

func sayHello() {
    // Hello World!
}
sayHello() // Hello World!

func sum(x int, y int) int {
    return x + y
}
sum(3, 7) // 10

func doubleAndTriple(x int) (double, triple int) {
    double = x * 2
    triple = x * 3
    return
}
d, t := doubleAndTriple(5)
// d = 10
// t = 15

_, t := doubleAndTriple(3)
// t = 9

var aux = 0
func switchValuesAndDouble(x, y int) {
    aux = x
    defer aux = 0
    x = y * 2
    y = aux * 2
}

a, b = 2, 5
switchValuesAndDouble(2, 5)
// a = 10
// b = 4
// aux = 0

func calc(fn func(int, int) int) int {
    return fn(2, 6)
}

func sum(x, y int) int {
    return x + y
}

func mult(x, y int) int {
    return x * y
}

calc(sum) // 8
calc(mult) // 12
calc(
    func(x, y int) int {
        return x / y
    }
) // 3

func calc() func(int) int {
    value := 0
    return func(x int) int {
        value += x
        return value
    }
}

calculator := calc()
calculator(3) // 3
calculator(45) // 48
calculator(12) // 60

Structs

Structs are a way to arrange data in specific formats.

type Person struct {
    Name string
    Age int
}

person := Person{"John", 34}
person.Name // "John"
person.Age // 34

person2 := Person{Age: 20}
person2.Name // ""
person2.Age // 20

person3 := Person{}
person3.Name // ""
person3.Age // 0

Maps

var cities map[string]string
cities = make(map[string]string)
cities // nil

// Insert
cities["NY"] = "EUA"

// Retrieve
newYork = cities["NY"]
newYork

// Delete
delete(cities, "NY")

// Check if a key is setted
value, ok := cities["NY"]
ok // false
value // ""

Pointers

var value int
var pointer *int

value = 3
pointer = &value
pointer // 3

pointer = 20
pointer // 20
pointer += 5
pointer // 25

type Struct struct {
    X int
}
s := Struct{3}
pointer := &s

s.X // 3

Methods and Interfaces

type Dog struct {
    Name string
}

func (dog *Dog) bark() string {
    return dog.Name + " is barking!"
}

dog := Dog{"Rex"}
dog.bark()
type Vehicle interface {
    Accelerate()
}

type Car struct {}

func (car *Car) Accelerate() {
    return "Car is moving on ground"
}

Errors

import "errors"
func firstLetter(text string) (string, error) {
    if len(text) < 1 {
        return nil, errors.New("Parameter text is empty")
    }
    return string(text[0]), nil
}

a, errorA := firstLetter("Wow")
a // "W"
errorA // nil

b, errorB := firstLetter("")
b // nil
errorB // Error("Parameter text is empty")

Testing

// main.go
func Sum(x, y int) int {
    return x + y
}

// main_test.go
import ( 
    "testing"
    "reflect"
)

func TestSum(t *testing.T) {
    x, y := 2, 4
    expected := 2 + 4
    
    if !reflect.DeepEqual(Sum(x, y), expected) {
        t.Fatalf("Function Sum not working as expected")
    }
}

Concurrency

func show(from string) {
    for i := 0; i < 3; i++ {
        fmt.Printf("%s : %d\n", from, i)
    }
}

func main() {
    show("blocking1")
    show("blocking2")
    fmt.Println("done")
}

/*  blocking1: 0
    blocking1: 1
    blocking1: 2
    blocking2: 0
    blocking2: 1
    blocking2: 2
    done 
*/


func main() {
    go show("routine1")
    go show("routine2")
    go func() {
        fmt.Println("going")
    }()
    
    time.Sleep(time.Second)
    fmt.Println("done")
}

/*  Obs: The result will depends of what processes first
    routine2: 0
    routine2: 1
    routine2: 2
    going
    routine1: 0
    routine1: 1
    routine1: 2
    done
*/

msgs := make(chan string)
go func(channel chan string) {
    channel <- "ping"
}(msgs)

go func(channel chan string) {
    channel <- "pong"
}(msgs)

fmt.Println(<-msgs) // pong
fmt.Println(<-msgs) // ping


numbers := make(chan int, 2)
msgs<-0
msgs<-1
msgs<-2

numbers := make(chan int)

go func(sender chan<- int) {
    sender <- 10
}(numbers)

go func(receiver <-chan int) {
    fmt.Println(<-receiver) // 10
}(numbers)

time.Sleep(time.Second)


c1 := make(chan string)
c2 := make(chan string)

select {
case msg1 := <-c1:
    fmt.Println("received", msg1)
case msg2 := <-c2:
    fmt.Println("received", msg2)
default:
    fmt.Println("no messages")
}

go func() {
    time.Sleep(1 * time.Second)
    c1 <- "channel1 : one"
}()

go func() {
    time.Sleep(2 * time.Second)
    c2 <- "channel2 : one"
}()

for i := 0; i < 2; i++ {
    select {
    case msg1 := <-c1:
        fmt.Println("received", msg1)
    case msg2 := <-c2:
        fmt.Println("received", msg2)
    }
}

/*
    no messages
    received channel1: one
    received channel2: one
*/

channel := make(chan int, 5)
for i := 0; i < 5; i++ {
    channel <- i
}
close(channel)

for value := range channel {
    fmt.Println(value)
}
/*
    0
    1
    2
    3
    4
*/

Package fmt

import "fmt"fmt.Print("Hello World") // Print in console
fmt.Println("Hello World") // Print and add a new line in end
fmt.Printf("%s is %d years old", "John", 32) // Print with formatting
fmt.Errorf("User %d not found", 123) // Print a formatted error

 

참고

https://kubernetes7.medium.com/golang-cheet-sheet-eebf6175f9b0

반응형

'개발 > go' 카테고리의 다른 글

Resty ( Http & Rest Client library)  (0) 2022.08.26
GoDS ( Go Data Structures )  (0) 2022.08.24
Viper  (0) 2022.08.23
cobra library 사용법  (0) 2022.08.22
모둘과 패키지  (0) 2022.08.22
Comments