Golang recurses and outputs its own source code

Time:2021-10-16

Question: [2min let’s think for ourselves]

Can a program P output its own source code after running? And the format shall be consistent (line feed, space, etc.)

 

reflection:

The essence of this problem is a recursive problem. It is set that P generates G after running, that is, P – > G & & P = = g:

1. P needs to set a string me to store its own source code

2. The assignment content of p.me is the line from the beginning of P source file to p.me (the blue part and red part in P are the same). At this time, the content in p.me is the source code of assignment from the beginning of G to g.me (the red part in G)

3. P then continues to print out the content assigned by g.me (the blue part in G)

 

In this case, it is necessary to ensure that PPrint me is in front, and the assignment of me is in the backWe can just think that init function in golang executes before main function and has nothing to do with the front and back of the line. Therefore, we can put the assignment of p.me in init and the number of lines is greater than the number of lines of main. In this way, the source code in P has been determined when assigning p.me

  

Source code:

1 package main
 2 
 3 import (
 4     "fmt"
 5 )
 6 
 7 var me string
 8 
 9 func main() {
10     fmt.Print(me)
11     fmt.Print(string(rune(96)))
12     fmt.Print(me)
13     fmt.Print(string(rune(96)) + "\n}")
14 }
15 
16 func init() {
17     me = `package main
18 
19 import (
20     "fmt"
21 )
22 
23 var me string
24 
25 func main() {
26     fmt.Print(me)
27     fmt.Print(string(rune(96)))
28     fmt.Print(me)
29     fmt.Print(string(rune(96))+"\n}")
30 }
31 
32 func init() {
33     me = `
34 }

You can see that the red and blue parts of the code are exactly the same

When line 10 is executed, lines g 1-17 are output, with the red part

When line 11 is executed, the output is the `, yellow part in line g 17

When line 12 is executed,   The output is line g 17-33, the blue part

When line 13 is executed, the output is line g 33-34, the green part

 

You can also try other languages