Junior — Middle
How can you limit the use of the same standard methods in Go when using manual calls?
sobes.tech AI
Answer from AI
In Go, standard methods, such as interface methods, are called automatically when using the corresponding types. If you need to restrict or control the application of these methods during manual calls, you can:
- Use composition instead of inheritance to explicitly control which methods are available.
- Create wrappers around types that override or hide standard methods.
- Use interfaces to restrict the set of available methods.
Example with a wrapper:
package main
import "fmt"
type MyType struct{}
func (m MyType) String() string {
return "MyType String"
}
// Wrapper that hides the String method
type Wrapper struct {
inner MyType
}
func (w Wrapper) Print() {
fmt.Println("Custom print without String method")
}
func main() {
m := MyType{}
w := Wrapper{inner: m}
fmt.Println(m.String()) // call to the standard method
w.Print() // call to the custom method without String
}
Thus, you can control which methods are accessible and how they are called.