Getting a pointer to a constant in Go

submited by
Style Pass
2024-11-25 21:00:04

In Go, sometimes you need to get a pointer to a constant value. This is normally easy, but only if you have a value, not a constant. Let's say you or a friend are dealing with the AWS S3 API and you need to pass a value to one of the parameters:

Making variables and passing things as arguments to functions aren't the only way to do this, there's also a trick I learned by reading Kubernetes source code. I'll paste an example and then explain how it works:

This works by creating an anonymous string slice with one member "foo", grabs the first element of that slice, and gets the pointer to it. This makes the code look kinda cursed:

Facts and circumstances may have changed since publication. Please contact me before jumping to conclusions if something seems wrong or unclear.

Leave a Comment