Hello, I’m fried fish.

When you look at the code for the Go1.18 generic, you may have noticed a new keyword, any.

Examples are as follows:

func Print[T any](s []T) {}
Copy the code

I haven’t mentioned this before, but any of you think this keyword is just generic code?

It’s not… In this new Go1.18 update, any appears as a new keyword, and any has a real name, which is essentially an alias for interface{} :

type any = interface{}
Copy the code

That is, in regular code, you can also use:

func f(a any) {
	switch a.(type) {
	case int:
		fmt.Println("Fish in the brain.")
	case float64:
		fmt.Println("Fried fish in the brain.")
	case string:
		fmt.Println("Brain goes into fried fish.")}}func main(a) {
	f(2)
	f(3.1415)
	f("Good fried fish!")}Copy the code

The new any keyword will be easier to use than interface{} because it has fewer words and is faster.

The comparison after adding the new keyword is as follows:

Long statement A short statement
func f[T interface{}](s []T) []T func f[T any](s []T) []T
func f(a interface{}) func f(a any)
var a interface{} var a any

After we understand its convenience, in terms of code consistency and readability, there are some problems, which will cause some confusion.

So a couple of days ago someone came up with a call to all: rewrite Interface {} to any.

You might think it’s a manual modification? That is definitely not true. Go officially initiated CL for batch modification.

In daily engineering, we can also use the Go tool chain directly to achieve replacement, just like them.

As follows:

gofmt -w -r 'interface{} -> any'. /...Copy the code

Interface {} will be a thing of the past, replaced by any.

Clearly, the answer is no. Since Go1 has compatibility guarantees, it will definitely not be removed at this stage. However, later on in our Go project, some people use any and others use interface{}, which hurts the code readability.

We can also use the Gofmt tool to force all interface{} to be any in the Linter process to achieve code consistency.

This change feels like an aesthetic issue. What do you think about it? If there are any aliases you would like to see, please leave a comment in the comments section 🙂

If you have any questions, welcome feedback and communication in the comments section. The best relationship is mutual achievement. Your praise is the biggest motivation for the creation of fried fish, thank you for your support.

This article is constantly updated. You can read it on wechat by searching “Brain into fried fish”. GitHub github.com/eddycjy/blo… Already included, learning Go language can see Go learning map and route, welcome Star urged more.