github.com/pkujhd/goloader@v0.0.0-20240411034752-1a28096bd7bd/examples/base/base.go (about)

     1  package base
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"sync"
     7  )
     8  
     9  func init() {
    10  	fmt.Println("base init")
    11  }
    12  
    13  type Vertex struct {
    14  	X, Y int
    15  }
    16  
    17  func (v *Vertex) Print() {
    18  	fmt.Println("print", v)
    19  }
    20  
    21  type PrintInf interface {
    22  	Print()
    23  }
    24  
    25  func main() {
    26  	var (
    27  		v1 = Vertex{1, 2}
    28  		v2 = Vertex{X: 1}
    29  		v3 = Vertex{}
    30  		p  = &Vertex{1, 2}
    31  	)
    32  
    33  	fmt.Println(Vertex{1, 2})
    34  	fmt.Println(v1, p, v2, v3)
    35  	fmt.Printf("%#v %#v %#v %#v\n", v1, p, v2, v3)
    36  
    37  	var inf PrintInf = p
    38  	inf.Print()
    39  
    40  	{
    41  		names := [4]string{
    42  			"John",
    43  			"Paul",
    44  			"George",
    45  			"Ringo",
    46  		}
    47  		fmt.Println(names)
    48  	}
    49  
    50  	{
    51  		s := []struct {
    52  			i int
    53  			b bool
    54  		}{
    55  			{2, true},
    56  			{3, false},
    57  		}
    58  		fmt.Println(s)
    59  	}
    60  
    61  	{
    62  		var m = map[string]Vertex{
    63  			"Bell Labs": Vertex{
    64  				40, -74,
    65  			},
    66  			"Google": Vertex{
    67  				37, -122,
    68  			},
    69  		}
    70  		fmt.Println(m)
    71  	}
    72  
    73  	{
    74  
    75  		wg := new(sync.WaitGroup)
    76  		whatAmI := func(i interface{}) {
    77  			switch t := i.(type) {
    78  			case bool:
    79  				fmt.Println("I'm a bool")
    80  			case int:
    81  				fmt.Println("I'm an int")
    82  			default:
    83  				fmt.Printf("Don't know type %T\n", t)
    84  			}
    85  			wg.Done()
    86  		}
    87  		wg.Add(1)
    88  		go whatAmI(true)
    89  		wg.Add(1)
    90  		go whatAmI(1)
    91  		wg.Add(1)
    92  		whatAmI("hey")
    93  		wg.Wait()
    94  	}
    95  
    96  	recoverTest()
    97  
    98  	{
    99  		pos, neg := adder(), adder()
   100  		for i := 0; i < 10; i++ {
   101  			fmt.Println(
   102  				pos(i),
   103  				neg(-2*i),
   104  			)
   105  		}
   106  	}
   107  
   108  }
   109  
   110  func adder() func(int) int {
   111  	sum := 0
   112  	return func(x int) int {
   113  		sum += x
   114  		return sum
   115  	}
   116  }
   117  
   118  func recoverTest() {
   119  	defer logPanic()
   120  	panic("this is a panic test")
   121  }
   122  
   123  func logPanic() {
   124  	if r := recover(); r != nil {
   125  		trace := make([]byte, 1024)
   126  		count := runtime.Stack(trace, false)
   127  		fmt.Printf("panic: %s\nStack of %d bytes:\n%s\n", r, count, trace[:count])
   128  	}
   129  }