Some of my favorite tidbits from the past year of working with Go. One of the best ways to learn something new is to write down something you’ve learned about it regularly. Over the past year, I’ve been doing this with the Go programming language. Here are some of my favorite lesser-known tidbits about the language. Ranging Directly over Integers As of Go 1.22, you can range over an integer: for i := range 10 { fmt.Println(i + 1) // 1, 2, 3 ... 10 } Renaming Packages You can use Go’s LSP to rename packages, not just regular variables. The newly named package will be updated in all references. As a bonus, it even renames the directory! Constraining Generic Function Signatures You can use the ~ operator to constrain a generic type signature. For instance, for typed constants, you can do this: package main import ( "fmt" ) type someConstantType string const someConstant someConstantType = "foo" // Underlying type is a string func main() { msg := buildMessage(someConstant) fmt.Println(msg) } func buildMessage[T ~string](value T) string { // This accepts any value whose underlying type is a string return fmt.Sprintf("The underlying string value is: '%s'", value) } This is really useful when the concrete type is a typed constant in Go, much like an enum in another language. Index-based String Interpolation You can do indexed based string interpolation in Go: package main import ( "fmt" ) func main() { fmt.Printf("%[1]s %[1]s %[2]s %[2]s %[3]s", "one", "two", "three") // yields "one one two two three" } This is helpful if you have to interpolate the same value multiple times and want to reduce repetition and make the interpolation easier to follow. The time.After function The time.After function creates a channel that will be sent a message after x seconds. When used in combination with a select statement it can be an easy way of setting a deadline for another routine. package main import ( "fmt" "time" ) func main() { ch := make(chan string, 1) go func() { time.Sleep(2 * ...
First seen: 2025-10-22 08:19
Last seen: 2025-10-22 19:26