supereagle / experiences

Summary of practical experience in work.
2 stars 0 forks source link

Golang knowledge points #16

Open supereagle opened 7 years ago

supereagle commented 7 years ago

Category

EBooks

References

supereagle commented 7 years ago

Object中的fields必须是exported,才能被JSON/YAML Marshal/Unmarshal

Examples

Reference

supereagle commented 7 years ago

Embedding Structs

Reference

supereagle commented 7 years ago

Judge the Existence of File/Directory

Reference

supereagle commented 7 years ago

Make slice instead of declaring it to improve efficiency when its length is known

type User struct {
    name    string
    address string
}

// Good practice with high efficiency
func getUsernames(users ...User) []string {
    usernames := make([]string, len(users))
    for _, user := range users {
        usernames = append(usernames, user.name)
    }

    return usernames
}

// Bad practice with low efficiency
func getUsernames(users ...User) []string {
    var usernames []string
    for _, user := range users {
        usernames = append(usernames, user.name)
    }

    return usernames
}
supereagle commented 7 years ago

Declare varables with := is not allowed outside function body

package main

import "fmt"

name := "robin"

func main() {
    fmt.Printf("Name is %s\n", name)
}

Compile Error:

.\main.go:5: syntax error: non-declaration statement outside function body

Solution: The declaration name := "robin" should be changed to var name string = "robin".

supereagle commented 7 years ago

Declaration and usage of channel array

package main

import (
    "fmt"
    "time"
)

func main() {

    // Need to declare for each element of the channel array.
    var metrics [3]chan bool
    for i := range metrics {
        metrics[i] = make(chan bool)
    }

    go func() {
        metrics[0] <- isHigh()
    }()

    go func() {
        metrics[1] <- isSmart()
    }()

    go func() {
        metrics[2] <- isRich()
    }()

    for _, metric := range metrics {
        if result := <-metric; !result {
            fmt.Println("Failure")
            return
        }
    }

    fmt.Println("Success")
}

func isHigh() bool {
    fmt.Println("Measuring the high")
    time.Sleep(1 * time.Second)

    return false
}

func isSmart() bool {
    fmt.Println("Measuring the IQ")
    time.Sleep(5 * time.Second)

    return true
}

func isRich() bool {
    fmt.Println("Measuring the treasure")
    time.Sleep(3 * time.Second)

    return false
}
supereagle commented 7 years ago

Can not take the address of const

package main

import "fmt"

func main() {
    const pi = 3.1415926

    // Error: Cannot take the address of pi.
    // address := &pi

    // Correct: Use a temp variable to store the value of const, and then take its address.
    tempVar := pi
    address := &tempVar

    fmt.Println(*address)
}

References