preface

When looking at a bottom library, I saw a more strange writing method, so I have this article.

Two main issues are discussed:

1. Use compilation to determine whether the Golang interface is implemented. 2

The body of the

1. Use new() to determine whether the Golang interface is implemented

Look at the underlying common link pool library, there is this line of code:

var _ Pooler = new(WeightedRoundRobin)
Copy the code

Pooler is an interface type.

type Pooler interface {
    // ...
}
Copy the code

At first, I was confused. Why did I abandon the tune after new?

This is to verify whether the interface is implemented.

After looking at the code a little bit more, I realized that there are a lot of places like this.

So here we Get.

Explanation: If the sub-interface is not implemented, the IDE will have a red line on the one hand and an error on the other hand at compile time. Two tips to ensure that the interface to write the underlying code is implemented.

2. The extended difference between make and new

You can use go test to define an interface in the _test.go file. As judged above, there will be a waste of memory”

Here are two points: 1. Go test method is definitely feasible. But there is no guarantee that the programmer will actually remember to perform the test (the process that is not mandatory). But directly through the above method, it will throw errors during compilation, this is a must go process, so the above method is recommended.

2. New occupies memory? New: Allocates memory, but does not initialize the memory, only zeros the memory and returns a pointer.

Make: allocates memory, returns a zero value for the initialized structure.



Back to the body, although memory is requested, it is not much memory and is reclaimed in a GC after initialization. So it’s okay.

There’s also no efficiency problem, compiled languages, you know.

Also verify a new and take the difference between address and make code:

func main(a) {
 a1 := new([]int)
 a2:= &[]int{}
 a3:= make([]int.0)

 fmt.Println(a1,a2,a3,a1==a1)
}
Copy the code

Appendix: The difference between Golang New and Make

Expansion of memory footprint, today saw a way to write.

var _ Tester = (*Test)(nil)
Copy the code

The difference between this and new is that new is checked at compile time and this is checked at run time

How to determine if the Golang interface is implemented?

This article is formatted using MDNICE