nil channel VS closed channel
Posted on August 16, 2020
(Last modified on August 27, 2020)
| 2 minutes
| Kinshuk Chandra
The zero value of channel type is nil, and the send and receive operations on a nil channel will always block. Check the following example:
package main import "fmt" func main() { var ch chan int go func(c chan int) { for v := range c { fmt.Println(v) } }(ch) ch <- 1 } The running result is like this:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send (nil chan)]: main.
[Read More]"go build" and "go install"
Posted on August 16, 2020
(Last modified on August 27, 2020)
| 3 minutes
| Kinshuk Chandra
Let’s tidy up the $GOPATH directory and only keep Go source code files left over:
# tree . ├── bin ├── pkg └── src ├── greet │ └── greet.go └── hello └── hello.go 5 directories, 2 files The greet.go is greet package which just provides one function:
# cat src/greet/greet.go package greet import "fmt" func Greet() { fmt.Println("नमस्ते किंशुक!") } While hello.go is a main package which takes advantage of greet and can be built into an executable binary:
[Read More]"nil slice" vs "nil map"
Posted on August 16, 2020
(Last modified on August 27, 2020)
| 2 minutes
| Kinshuk Chandra
Slice and map are all reference types in Go, and their default values are nil:
package main import "fmt" func main() { var ( s []int m map[int]bool ) if s == nil { fmt.Println("The value of s is nil") } if m == nil { fmt.Println("The value of m is nil") } } The result is like this:
The value of s is nil The value of m is nil When a slice’s value is nil, you could also do operations on it, such as append:
[Read More]error vs errors
Posted on August 16, 2020
(Last modified on August 27, 2020)
| 2 minutes
| Kinshuk Chandra
Handling errors is a crucial part of writing robust programs. When scanning the Go packages, it is not rare to see APIs which have multiple return values with an error among them. For example:
func Open(name string) (*File, error)
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.
[Read More]Pass slice as a function argument
Posted on August 16, 2020
(Last modified on August 27, 2020)
| 2 minutes
| Kinshuk Chandra
In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now.
[Read More]