Source: Basic Skills
6L and 6g in the original article are not found in the Go tool, check the relevant information on the Internet and have the following supplements: The tools used are go tool compile and Go tool objdump
go tool
Copy the code
Here I highlight the two most commonly used tools: Go tool compile and Go Tool objdump. When we rolled out the Go compilation, there was a slang phrase in the industry:
There is almost no Go assembly problem that cannot be solved without a Go tool compile. If not, use Go Tool objdump and you will always know what is going on.
Let’s see what these two instructions mean in specific situations:
Go tool compile -s main.go # Decompile code into assembly code.
Go Tool objdump # can be used to view machine code, assembly instructions, offsets of any function. (Go source code has a CMD /internal/goobj package, you can read the.o file redirection information, better)
Go tool objdump -s binary # objdump prints a disassembly of all text symbols (code) in a binary file. If the -s option is present, objdump will disassemble only symbols whose names match the regular expression.
Let’s write a small case for assembly debugging practice:
package main
import "fmt"
func main() {
var a = "hello"
var b = []byte(a)
fmt.Println(b)
}
Copy the code
Check it out with a disassembly tool:
go tool compile -S ./hello.go | grep "hello.go:5"
Copy the code
This command produces the.o object file and outputs the assembly content of the object. Following the pipe, grep hello.go to compile the fifth line of assembly code. Most of the assembly code here is not really understood, we just need it to call one of the functions to know.
For starters, you don’t need to know everything to learn Go assembly, just a few critical paths to what’s going on. Such as the key here is “the runtime stringtoslicebyte (SB)”, that is, we need to get the string into a byte array, the bottom will call this function.
With this approach we can solve the first problem mentioned in the previous article:
Scenario 1, how fast are these two pieces of code running? The first one is faster than the second one?
1 package main type person struct {age int} func main() {var a = &person{111} println(a)}Copy the code
Struct {age int} func main() {var b = person {111} var a = &b println(a)}Copy the code
Let’s see what line 8 of the first code compiles:
Look again at lines 8 and 9 of the second code:
From this, we can conclude that a one-line version of the code and a two-line version of the code will compile exactly the same, with no difference.
Study article: www.modb.pro/db/112650