Closures in Go

In Go, it’s pretty easy to write an anonymous function. package main import "fmt" func main() { func(s string){ fmt.Println("s is:", s) }("hello world") } Running the above code produces: $ go run main.go s is: hello world You can even assign the anonymous function to a variable like so: package main import "fmt" func main() { myFunc := func(s string){ fmt.Println("s is:", s) } myFunc("hello again, world!") } Now we get this output from the above code:...

2022-07-13

Generics in Go 1.18

In Go 1.18, we get access to Genrics. Huzzah! Here’s an basic example of how to use them: package main import ( "fmt" ) func PrintAge[age float32 | int64](myAge age) { fmt.Printf("age: %s \t type: %T\n", myAge, myAge) } func main() { var age1 float32 = 30.5 var age2 int64 = 32 PrintAge(age1) PrintAge(age2) } Running the above program gives us the below output. You can see that it happily accepted the float32 and int64 values without issue....

2022-07-12

Go defer

defer in go is used to run a function later on. Specifically, the specified function will run when the enclosing function returns. There’s no clean equivalent to this in Python that I’ve found. The quintessential example is closing a file handle as your program exits. Example package main import ( "fmt" "os" ) func main() { file := createFile("/tmp/testingdefer.txt") defer closeFile(file) writeFile(file) } func createFile(path string) (file *os.File) { fmt.Println("creating file: ", path) file, _ = os....

2021-07-20

Empty Go Interfaces

When declaring function parameters in Go, you must type the incoming data. Here’s an example: package main import "fmt" func print_stuff(s string) { fmt.Println(s) } func main() { print_stuff("Passing string!") } s string indicates that we’re passing a variable of type string into the function. This prevents us from from passing into variables of any other type. For example, this will fail with ./prog.go:10:17: cannot use 42 (type untyped int) as type string in argument to example_str if you try to pass an integer....

2021-07-11

golang

go doc Display doc for current package: go doc Display doc for type in current package: go doc TYPE or go doc -all TYPE go test Run all tests: Run all tests: go test ./... Run all tests in package: go test modulename/pkg/packagename/ Run all tests in file: go test path/to/file_test.go Run subset of tests: Run function tests: go test path/to/file_test.go -run FUNCTION_TEST_NAME Run a single test in function tests: go test path/to/file_test....