Bracket syntax for custom struct types in Go

I’m willing to create C++ STL in Go. Is there a way to create custom structs that implement bracket syntax for index accessing? Assume this is my array type: type Array[T any] struct { values []T } Is there any way I can add bracket syntax indexation instead of Array.At() or any other? I want… Read More Bracket syntax for custom struct types in Go

Passing pointer of string to a function leads to the wrong string being printed

I have the following program (simplified as much as possible): package main import "fmt" type Test struct { Str *string } func main() { arr := []string{"vanC", "vanD"} arr2 := make([]Test, 0) for _, element := range arr { fmt.Println(element, &element) arr2 = append(arr2, Test{ Str: &element, }) } fn(arr2) } func fn(arr2 []Test) {… Read More Passing pointer of string to a function leads to the wrong string being printed

Go return struct as JSON in HTTP request

I’ve defined the following struct in Go: type repoStars struct { name string owner string stars int } And I’ve created an array repoItems := []repoStars{} which has multiple items of the struct above. This is how repoItems looks like: I’m trying to return those items as a JSON response: w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(repoItems) And it… Read More Go return struct as JSON in HTTP request

Slices return unexpected length

I’m studying Golang and I stopped by this and puzzled me. package main import "fmt" func main() { month := […]string{1: "Jan", 2: "Fab", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} fmt.Println(cap(month)) summer := month[6:9] Q2 := month[4:7] fmt.Println(cap(Q2)) fmt.Println(len(Q2)) fmt.Println(cap(summer)) fmt.Println(len(summer))… Read More Slices return unexpected length