西维蜀黍

【Golang】内存管理

  ...


【Golang】slice 分析和实现

Analysis

Slice internals

A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).

Our variable s, created earlier by make([]byte, 5), is structured like this:

The length is the number of elements referred to by the slice. The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer).

  ...


【Golang】源码 - unsafe包

Overall

Pointer represents a pointer to an arbitrary type. There are four special operations available for type Pointer that are not available for other types:

  • A pointer value of any type can be converted to a Pointer.
  • A Pointer can be converted to a pointer value of any type.
  • A uintptr can be converted to a Pointer.
  • A Pointer can be converted to a uintptr.

Pointer therefore allows a program to defeat the type system and read and write arbitrary memory. It should be used with extreme care.

The following patterns involving Pointer are valid.

  ...


【Golang】Code Review

Summary

  • Use goimports to standardise imports

    • a superset of gofmt which additionally adds (and removes) import lines as necessary.
  • godoc

  • gofmt

  • go lint

Flow

Indent Error Flow

Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first. This improves the readability of the code by permitting visually scanning the normal path quickly. For instance, don’t write:

if err != nil {
	// error handling
} else {
	// normal code
}
  ...


【Golang】empty Slice和nil Slice

Best Practise

When declaring an empty slice, prefer

// nil slice
var t []string

over

// empty slice, or name non-nil but zero-length slice
t := []string{}

The former declares a nil slice value, while the latter is non-nil but zero-length. They are functionally equivalent—their len and cap are both zero—but the nil slice is the preferred style.

Note that there are limited circumstances where a non-nil but zero-length slice is preferred, such as when encoding JSON objects (a nil slice encodes to null, while []string{} encodes to the JSON array []).

When designing interfaces, avoid making a distinction between a nil slice and a non-nil, zero-length slice, as this can lead to subtle programming errors.

  ...