今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

Method Values vs Method Expressions in Go: A Distinction Worth Knowing

Gabriel Anhaia 2026年07月03日 23:36 1 次阅读 来源:Dev.to

Book: The Complete Guide to Go Programming Also by me: Hexagonal Architecture in Go — the companion book in the Thinking in Go series My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You are wiring an HTTP router. You have a Server struct with a handler method, and you want to register it. So you write mux.HandleFunc("/users", srv.ListUsers) and it works. You never stop to ask what srv.ListUsers actually is as an expression. It is a method value. Go took the method, bound it to srv , and handed you back a plain func(http.ResponseWriter, *http.Request) . That binding is the thing doing the quiet work in half the handler wiring you write. There is a second form the Go spec gives you, and most Go developers never type it on purpose: the method expression, Server.ListUsers , which produces a function that takes the receiver as its first argument. Same method, different shape, different use. These two live in the Go spec and they are worth telling apart, because the compiler will happily let you reach for the wrong one. The two forms, side by side Start with a small type and one method. type Greeter struct { prefix string } func ( g Greeter ) Say ( name string ) string { return g . prefix + " " + name } A method value binds the receiver now: g := Greeter { prefix : "hello" } say := g . Say // method value, receiver g is captured fmt . Println ( say ( "ana" )) // "hello ana" say has type func(string) string . The receiver is gone from the signature because Go already stored g inside the closure. Call it later, from anywhere, and it still remembers g . A method expression leaves the receiver open: say := Greeter . Say // method expression, no receiver yet fmt . Println ( say ( g , "ana" )) // "hello ana" say here has type func(Greeter, string) string . The receiver became the first parameter. You supply it at the call site, every time. Same method name. g.Say reads the value g ; Greeter.Sa

本文内容来源于互联网,版权归原作者所有
查看原文