Skip to content

Instantly share code, notes, and snippets.

@zycbobby
Last active November 3, 2015 03:51
Show Gist options
  • Save zycbobby/2297b532e867bb2b6ddc to your computer and use it in GitHub Desktop.
Save zycbobby/2297b532e867bb2b6ddc to your computer and use it in GitHub Desktop.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := File{fd, name, nil, 0}
return &f
}
# The reason for the distinction is that these three types represent, under the covers, references to data structures that must be initialized before use.
var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
// Unnecessarily complex:
var p *[]int = new([]int)
*p = make([]int, 100, 100)
// Idiomatic:
v := make([]int, 100)
@zycbobby
Copy link
Author

zycbobby commented Nov 3, 2015

data-constructor.go

  • Other than using new(File)因为这个只是把内存初始化为0,除了Buffer一般用不到
  • it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns.

return 的另外一种写法

return &File{fd: fd, name: name}

As a limiting case, if a composite literal contains no fields at all, it creates a zero value for the type. The expressions new(File) and &File{} are equivalent.

NewFile是一种推崇的constructor写法

@zycbobby
Copy link
Author

zycbobby commented Nov 3, 2015

make slice

  • Remember that make applies only to maps, slices and channels and does not return a pointer. To obtain an explicit pointer allocate with new or take the address of a variable explicitly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment