Skip to content

Instantly share code, notes, and snippets.

@holmberd
Last active December 9, 2023 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holmberd/edf1e94fd9788b4171fdc26d3c60cbd9 to your computer and use it in GitHub Desktop.
Save holmberd/edf1e94fd9788b4171fdc26d3c60cbd9 to your computer and use it in GitHub Desktop.
Go Notes

Slices

// https://www.dolthub.com/blog/2023-10-20-golang-pitfalls-3/
type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

sliceA := []int{1, 2, 3}
sliceB := append(sliceA, 4)
sliceC := append(sliceA, 5)
sliceC[0] = 0

fmt.Println(*(*slice)(unsafe.Pointer(&sliceA))) // prints {0xc00001a018 3 3}

Interfaces

If you assign a value to an interface, even if that value is nil, the interface itself is not nil.

type MyType struct{}

func (m *MyType) Write(p []byte) (n int, err error) {
	fmt.Println("called.")
	return len(p), nil
}

type MyInterface interface {
	MyMethod()
}

func main() {
	var myType *MyType // myType = nil
  test(myType)
  
  var myInterface MyInterface
	if myInterface == nil {
		fmt.Println("The interface is nil.")
	}
}

func test(out io.Writer) {
	if out != nil {
		fmt.Println("interface is not nil.")
	}

	if v, ok := out.(*MyType); ok && v == nil {
		fmt.Println("Underlying value of the interface is nil.")
	}
}
type MyInterface interface {
	MyMethod()
}

func main() {
	var myInterface MyInterface

	if myInterface == nil {
		fmt.Println("The interface is nil.")
	}
}

Strings

func main() {
    str := "你好" // Chinese characters for "Hello"

    // Accessing individual bytes (byte = uint8) in the string
    for i := 0; i < len(str); i++ {
	fmt.Printf("%U)", str[i])
    }
    fmt.Println()

    // Accessing individual runes (Unicode code points - UTF8, rune = int32) in the string
    for _, r := range str {
        fmt.Printf("%c ", r)
    }
    fmt.Println()
}

Equality

When comparing two instances of a value type in Go, it checks whether their field values are equal.

type someStr struct{ text string }

a := someString{"test1"}
b := someString{"test1"}

fmt.Println(a == b) // true

a = &someString{"test1"}
b = &someString{"test1"}

fmt.Println(a == b) // false

Reflect (Typeof)

reflect.TypeOf(v).String()

Type Assertion (InstanceOf)

type MyInt interface{}
var x MyInt = 5

res := x.(int)
fmt.Printf("type: %T value: %[1]v\n", res)

Interface assertion

// Animal interface
type Animal interface {
	Speak() string
}

// Trainer interface with an additional method
type Trainer interface {
	Train() string
}

// Dog type implementing both Animal and Trainer interfaces
type Dog struct{}

func (d Dog) Speak() string {
	return "Woof! Woof!"
}

func (d Dog) Train() string {
	return "Sit! Stay!"
}

type SpeakTrain interface {
	Speak() string
	Train() string
}

func main() {
	var t Trainer
	t = PoliceDog{}

	// Type assertion to access the larger set of methods in the Trainer interface
	if st, ok := x.(SpeakTrain); ok {
		fmt.Println("Train:", st.Train())
		fmt.Println("Speak:", st.Speak())
	} else {
		fmt.Println("Type assertion failed")
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment