https://github.com/uber-go/fx https://blog.huyage.dev/posts/simple-dependency-injection-in-go/ At Uber, it is a breeze to scaffold new Go applications. A simple-to-use dependency injection framework called Fx makes this possible. I will briefly discuss why you may want to use dependency injection in your Go application, introduce the Fx framework, and present an example application that takes advantage of Fx.
对于手动管理内存的语言,比如 C/C++,调用著名的malloc和new函数可以在堆上分配一块内存,这块内存的使用和销毁的责任都在程序员。一不小心,就会发生内存泄露,搞得胆战心惊。 但是 Golang 并不是这样,虽然 Golang 语言里面也有 new。Golang 编译器决定变量应该分配到什么地方时会进行逃逸分析。使用new函数得到的内存不一定就在堆上。堆和栈的区别对程序员“模糊化”了,当然这一切都是Go编译器在背后帮我们完成的。一个变量是在堆上分配,还是在栈上分配,是经过编译器的逃逸分析之后得出的结论。 一、 逃逸分析是什么 wiki定义 In compiler optimization, escape analysis is a method for determining the dynamic scope of pointers - where in the program a pointer can be accessed. It is related to pointer analysis and shape analysis. When a variable (or an object) is allocated in a subroutine, a pointer to the variable can escape to other threads of execution, or to calling subroutines. If an implementation uses tail call optimization (usually required for functional languages), objects may also be seen as escaping to called subroutines. If a language supports first-class continuations (as do Scheme and Standard ML of New Jersey), portions of the call stack may also escape. If a subroutine allocates an object and returns a pointer to it, the object can be accessed from undetermined places in the program — the pointer has “escaped”. Pointers can also escape if they are stored in global variables or other data structures that, in turn, escape the current procedure. Escape analysis determines all the places where a pointer can be stored and whether the lifetime of the pointer can be proven to be restricted only to the current procedure and/or threa.