Posts

Showing posts with the label Go

Slices as arguments in Golang

Image
I recently came across several examples of using slices as function arguments, which lead to unexpected results. This post focuses on these examples. First example. The slice is passed to the function as an argument where it will be modified. https://play.golang.org/p/r5mKX5ErwLC package main import "fmt" func change(abc []int) { for i := range abc { abc[i] = 4 } fmt.Println(abc) } func main() { abc := []int{1, 2, 3} change(abc) fmt.Println(abc) } Output: [4 4 4] [4 4 4] Someone might expect that when we pass a slice to a function, we will get a copy of it in the function, and the changes will only appear in the function. But this is not the case. Slices in Go have a base array and are passed by reference, not value. We just pass the slice reference to the function, then change it, and it changes the outer slice. Second example. https://play.golang.org/p/5ruLrp6ZJJc package main import "fmt" func change(abc ...

Usage of flag in New constructor of log package in Golang

Image
Package log in Golang provides simple functionality for logging. In previous post we made several examples of usage New constructor for Logger. In this post will be exposed examples of usage New and meaning of third argument of New constructor. Let's begin with the simplest example. We will make logger that logs messages to standard output: package main import ( "log" "os" ) func main() { logger := log.New(os.Stdout, "", log.Ldate) logger.Println("First log message") } Output: 2020/04/21 First log message Let me remind signature of New: func New(out io.Writer, prefix string, flag int) *Logger In example as out io.Writer we used os.Stdout - standard output. As flag int used const from log package - log.Ldate - it is integer 1 - provides the date in the local time zone: 2020/04/21. Total there are 8 such constants in log package: log.Ldate - integer 1 - the date in the local time zone: 2020/04...

Examples of log package in Golang

Image
Hi, everybody! Today we view at some examples of log package in Golang. Package log has constructor method New . Its signature is following: func New(out io.Writer, prefix string, flag int) *Logger It means we need argument out implementing interface io.Writer : type Writer interface { Write(p []byte) (n int, err error) } Let's create our simple one: import ( "fmt" ) type CustomWriter struct {} func(c *CustomWriter) Write(p []byte) (n int, err error) { fmt.Print(string(p)) return len(p), nil } Now look at example: package main import ( "fmt" "log" ) type CustomWriter struct {} func(c *CustomWriter) Write(p []byte) (n int, err error) { fmt.Print(string(p)) return len(p), nil } func main() { var logger = log.New(&CustomWriter{}, "", log.LstdFlags) logger.Println("First log message") } Output: 2020/04/18 23:59:18 First log message Let's look at ...