Created
August 18, 2017 06:21
-
-
Save tenntenn/134d6965f75efe5eb6f6edf7b0ebe509 to your computer and use it in GitHub Desktop.
Demo code in GolangUK 2017.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"go/ast" | |
"go/importer" | |
"go/parser" | |
"go/token" | |
"go/types" | |
"log" | |
) | |
func main() { | |
fset := token.NewFileSet() | |
f, err := parser.ParseFile(fset, "gopher.go", nil, 0) | |
if err != nil { | |
log.Fatal(err) | |
} | |
cfg := &types.Config{Importer: importer.Default()} | |
info := &types.Info{ | |
Defs: map[*ast.Ident]types.Object{}, | |
Uses: map[*ast.Ident]types.Object{}, | |
} | |
if _, err = cfg.Check("main", fset, []*ast.File{f}, info); err != nil { | |
log.Fatal(err) | |
} | |
ast.Inspect(f, func(n ast.Node) bool { | |
switch n := n.(type) { | |
case *ast.Ident: | |
if n.Name == "Gopher" && | |
(isNamed(info.Uses[n]) || isNamed(info.Defs[n])) { | |
fmt.Println(fset.Position(n.Pos())) | |
} | |
return false | |
} | |
return true | |
}) | |
} | |
func isNamed(o types.Object) bool { | |
if o == nil { | |
return false | |
} | |
_, ok := o.Type().(*types.Named) | |
return ok | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Gopher struct { | |
Gopher string `json:"gopher"` | |
} | |
func main() { | |
const gopher = "GOPHER" | |
gogopher := GOPHER() | |
gogopher.Gopher = gopher | |
fmt.Println(gogopher) | |
} | |
func GOPHER() (gopher *Gopher) { | |
gopher = &Gopher{Gopher: "gopher"} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment