In Go, the strings.Join function accepts slices of strings as input. This can be limiting when attempting to concatenate objects of different types. However, it would be convenient to define a custom ToString() method for arbitrary objects.
Go provides a straightforward way to achieve this functionality:
Package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}
In this example, the bin type is defined as a custom numeric type. The String() method is attached to the bin type, enabling the conversion of bin values to strings according to the desired format (binary representation in this case).
When running the provided code, you will observe the following output:
101010
This demonstrates how the custom ToString() method allows for the concatenation and printing of objects other than strings. The bin value (42) is effortlessly converted to its binary representation and displayed as "101010".
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3