Skip to content

Instantly share code, notes, and snippets.

@rhomel
Created January 24, 2019 03:22
Show Gist options
  • Save rhomel/cdaea7717334ed72a8a524e7614ffaa7 to your computer and use it in GitHub Desktop.
Save rhomel/cdaea7717334ed72a8a524e7614ffaa7 to your computer and use it in GitHub Desktop.
Experiments with GoLang Custom Types
package main
// Experiments with GoLang Custom Types
// Playground link: https://play.golang.org/p/rHu1CBj0GvE
import "fmt"
// We can create our own types based on the concrete types.
// But Go will not consider our type "MyString" as the same type as the concrete
// type "string"
type MyString string
func CustomStringType_Experiment() {
s := "hi"
fmt.Println(s) // "hi"
m := MyString("there")
fmt.Println(m) // "there"
// convert custom type back to concrete type
ms := string(m)
fmt.Println(ms) // "there"
// if m == ms { // compiler error: mismatching types MyString, string
// fmt.Println("m == ms")
// }
if string(m) == ms { // ok
fmt.Println("string(m) == ms")
}
}
// We can add methods to our custom types
type Strings []string
func (s *Strings) PrintValues() {
for _, str := range ([]string)(*s) { // but we have to type convert before use
fmt.Print(str, " ")
}
fmt.Println()
}
func AddFunctionToCustomType_Experiment() {
ss := Strings{"a", "b", "c"}
ss.PrintValues() // a b c
}
// Why would you want to do this?
// To satisfy an interface without using a struct.
type FunkyStringer []int
// satisfy fmt.Stringer interface
func (f FunkyStringer) String() string {
var str string
for _, val := range ([]int)(f) {
str = fmt.Sprintf("%s- %d\n", str, val)
}
return str
}
func RunFunkyStringer_Experiment() {
fs := FunkyStringer{3, 5, 7}
fmt.Print(fs)
// Output:
// - 3
// - 5
// - 7
fmt.Println(([]int)(fs)) // [3 5 7] (standard go value format)
}
func main() {
CustomStringType_Experiment()
AddFunctionToCustomType_Experiment()
RunFunkyStringer_Experiment()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment