any

Thanh Pham / Wed 23 Mar 2022

The introduction of anyas an alias forinterface{} is one of the most interesting changes in Go 1.18, beside generics and fuzzing.

For a long time people complained a lot about the name interface{} which is quite confusing for beginners, and the introduction of any completely resolved that issue. According to the Go team, any is equal to interface{} in all ways. That means you can replace interface{} by any in any case. Any is easier to understand and easier to write as well.

So, instead of writing:

func Print(s ...interface{}) {
	for _, v := range s {
		fmt.Print(v)
	}
}

You now can write:

func Print(s ...any) {
	for _, v := range s {
		fmt.Print(v)
	}
}

Or with generics:

func Print[T any](s ...T) {
	for _, v := range s {
		fmt.Print(v)
	}
}

It's clear to see that "print any" is much easier to understand than "print interface{}".

And for those who want to replace interface{} by any in legacy code, you can use gofmt to quickly do it for you:

gofmt -r "interface{} -> any" -w .

It's cool! But you might ask "But any is just interface{}?". The answer is "Yes, in all ways!". No magic here! It's just the name that makes more sense!

type any = interface{}
Next In
golang
Page Speed Insights

The smaller size of HTML, JS, CSS and Images the better the performance.

Page Speed Insights score of https://pthethanh.herokuapp.com/