github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/src/runtime/example_test.go (about) 1 // Copyright 2017 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package runtime_test 6 7 import ( 8 "fmt" 9 "runtime" 10 "strings" 11 ) 12 13 func ExampleFrames() { 14 c := func() { 15 // Ask runtime.Callers for up to 10 pcs, including runtime.Callers itself. 16 pc := make([]uintptr, 10) 17 n := runtime.Callers(0, pc) 18 if n == 0 { 19 // No pcs available. Stop now. 20 // This can happen if the first argument to runtime.Callers is large. 21 return 22 } 23 24 pc = pc[:n] // pass only valid pcs to runtime.CallersFrames 25 frames := runtime.CallersFrames(pc) 26 27 // Loop to get frames. 28 // A fixed number of pcs can expand to an indefinite number of Frames. 29 for { 30 frame, more := frames.Next() 31 // To keep this example's output stable 32 // even if there are changes in the testing package, 33 // stop unwinding when we leave package runtime. 34 if !strings.Contains(frame.File, "runtime/") { 35 break 36 } 37 fmt.Printf("- more:%v | %s\n", more, frame.Function) 38 if !more { 39 break 40 } 41 } 42 } 43 44 b := func() { c() } 45 a := func() { b() } 46 47 a() 48 // Output: 49 // - more:true | runtime.Callers 50 // - more:true | runtime_test.ExampleFrames.func1 51 // - more:true | runtime_test.ExampleFrames.func2 52 // - more:true | runtime_test.ExampleFrames.func3 53 // - more:true | runtime_test.ExampleFrames 54 }