Loading...
Loading...
Go data structures including allocation with new vs make, arrays, slices, maps, printing with fmt, and constants with iota. Use when working with Go's built-in data structures, memory allocation, or formatted output.
npx skill4agent add cxuu/golang-skills go-data-structuresSource: Effective Go
newmakenew(T)T*Tp := new(SyncedBuffer) // type *SyncedBuffer, zeroed
var v SyncedBuffer // type SyncedBuffer, zeroedbytes.Buffersync.Mutextype SyncedBuffer struct {
lock sync.Mutex
buffer bytes.Buffer
}
// Ready to use immediately upon allocationmake(T, args)T*Tmake([]int, 10, 100) // slice: length 10, capacity 100
make(map[string]int) // map: ready to use
make(chan int) // channel: ready to usevar p *[]int = new([]int) // *p == nil; rarely useful
var v []int = make([]int, 100) // v is a usable slice of 100 ints
// Idiomatic:
v := make([]int, 100)make// Struct with positional fields
f := File{fd, name, nil, 0}
// Struct with named fields (order doesn't matter, missing = zero)
f := &File{fd: fd, name: name}
// Zero value
f := &File{} // equivalent to new(File)
// Arrays, slices, maps
a := [...]string{Enone: "no error", Eio: "Eio", Einval: "invalid"}
s := []string{Enone: "no error", Eio: "Eio", Einval: "invalid"}
m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid"}[10]int[20]intfunc Sum(a *[3]float64) (sum float64) {
for _, v := range *a {
sum += v
}
return
}
array := [...]float64{7.0, 8.5, 9.1}
x := Sum(&array) // Pass pointer for efficiencyfunc (f *File) Read(buf []byte) (n int, err error)
// Read into first 32 bytes of larger buffer
n, err := f.Read(buf[0:32])len(s)cap(s)func append(slice []T, elements ...T) []Tx := []int{1, 2, 3}
x = append(x, 4, 5, 6)
// Append a slice to a slice
y := []int{4, 5, 6}
x = append(x, y...) // Note the ...picture := make([][]uint8, YSize)
for i := range picture {
picture[i] = make([]uint8, XSize)
}picture := make([][]uint8, YSize)
pixels := make([]uint8, XSize*YSize)
for i := range picture {
picture[i], pixels = pixels[:XSize], pixels[XSize:]
}Normative: This is required per Go Wiki CodeReviewComments.
var t []stringt := []string{}lencapnull[]string{}[]// nil slice → JSON null
var tags []string
json.Marshal(tags) // "null"
// empty slice → JSON array
tags := []string{}
json.Marshal(tags) // "[]"==var timeZone = map[string]int{
"UTC": 0*60*60,
"EST": -5*60*60,
"CST": -6*60*60,
}
offset := timeZone["EST"] // -18000seconds, ok := timeZone[tz]
if !ok {
log.Println("unknown time zone:", tz)
}
// Or combined:
if seconds, ok := timeZone[tz]; ok {
return seconds
}delete(timeZone, "PDT") // Safe even if key doesn't existmap[T]boolattended := map[string]bool{"Ann": true, "Joe": true}
if attended[person] { // false if not in map
fmt.Println(person, "was at the meeting")
}fmt| Function | Output |
|---|---|
| Formatted to stdout |
| Returns formatted string |
| Formatted to io.Writer |
| Default format |
fmt.Printf("Hello %d\n", 23)
fmt.Println("Hello", 23)
s := fmt.Sprintf("Hello %d", 23)%vfmt.Printf("%v\n", timeZone)
// map[CST:-21600 EST:-18000 MST:-25200 PST:-28800 UTC:0]%v%+v%#vtype T struct {
a int
b float64
c string
}
t := &T{7, -2.35, "abc\tdef"}
fmt.Printf("%v\n", t) // &{7 -2.35 abc def}
fmt.Printf("%+v\n", t) // &{a:7 b:-2.35 c:abc def}
fmt.Printf("%#v\n", t) // &main.T{a:7, b:-2.35, c:"abc\tdef"}| Format | Purpose |
|---|---|
| Type of value |
| Quoted string |
| Hex (strings, bytes, ints) |
String() stringfunc (t *T) String() string {
return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
}Sprintf%s// Bad: infinite recursion
func (m MyString) String() string {
return fmt.Sprintf("MyString=%s", m)
}
// Good: convert to basic type
func (m MyString) String() string {
return fmt.Sprintf("MyString=%s", string(m))
}iotatype ByteSize float64
const (
_ = iota // ignore first value (0)
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
)String()func (b ByteSize) String() string {
switch {
case b >= EB:
return fmt.Sprintf("%.2fEB", b/EB)
case b >= PB:
return fmt.Sprintf("%.2fPB", b/PB)
// ... etc
}
return fmt.Sprintf("%.2fB", b)
}Advisory: This is a best practice recommendation from Go Wiki CodeReviewComments.
bytes.Buffer[]byteBuffer// Dangerous: copying a bytes.Buffer
var buf1 bytes.Buffer
buf1.WriteString("hello")
buf2 := buf1 // buf2's internal slice may alias buf1's array!
buf2.WriteString(" world") // May affect buf1 unexpectedlyT*Tbytes.Buffersync.Mutexsync.WaitGroupsync.Cond// Bad: copying a mutex
var mu sync.Mutex
mu2 := mu // Copying a mutex is almost always a bug
// Good: use pointers or embed carefully
type SafeCounter struct {
mu sync.Mutex
count int
}
// Pass by pointer, not by value
func increment(sc *SafeCounter) {
sc.mu.Lock()
sc.count++
sc.mu.Unlock()
}| Topic | Key Point |
|---|---|
| Returns |
| Slices, maps, channels only; returns |
| Arrays | Values, not references; size is part of type |
| Slices | Reference underlying array; use |
| Maps | Key must support |
| Copying | Don't copy |
| Default format for any value |
| Struct with field names |
| Full Go syntax |
| Enumerated constants |