💻 Tech
In Go, type assertion is used to extract the value of an interface at runtime, similar to type casting in other languages. Type aliasing is used to create a new type from an existing type. Type conversion is used to convert a value from one type to another.
func main() {
type str string // type aliasing - a new type is created from an existing type (string)
var str1 interface{} = "hello"
var str2 str = str("hello") // type conversion - converting a value from one type (string) to another (str)
var str3 interface{} = str("hello")
fmt.Println(str1.(string)) // output: hello; type assertion - extracting the value of an interface at runtime
fmt.Println(str2) // output: hello
fmt.Println(str3.(str)) // output: hello
_, isStr := str1.(str) // type assertion but with second return value to check if the assertion is successful
fmt.Println(isStr) // output: false; str1 is of type string, not str
_, isString := str3.(string)
fmt.Println(isString) // output: false; str3 is of type str, not string
}