Working with Types
Act Based on Type
package golang
import (
"fmt"
)
func Execute(t any) {
switch x := t.(type) {
case string:
fmt.Println(x)
case int:
fmt.Printf("%d\n", x)
case bool:
fmt.Printf("%t\n", x)
case float64:
fmt.Printf("%f\n", x)
}
}
func DoIt() {
things := []any{"foo", 1, true, 6.4}
for _, t := range things {
Execute(t)
}
}
import (
"fmt"
)
func Execute(t any) {
switch x := t.(type) {
case string:
fmt.Println(x)
case int:
fmt.Printf("%d\n", x)
case bool:
fmt.Printf("%t\n", x)
case float64:
fmt.Printf("%f\n", x)
}
}
func DoIt() {
things := []any{"foo", 1, true, 6.4}
for _, t := range things {
Execute(t)
}
}
Check Object Type
As a function:
package golang
func IsString(s any) bool {
_, ok := s.(string)
return ok
}
func IsString(s any) bool {
_, ok := s.(string)
return ok
}
For example:
package golang
import (
"fmt"
)
func Execute(t any) {
s, ok := t.(string)
if ok {
fmt.Println(s)
}
}
func DoIt() {
things := []any{"foo", 1, true, 6.4}
for _, t := range things {
Execute(t)
}
}
import (
"fmt"
)
func Execute(t any) {
s, ok := t.(string)
if ok {
fmt.Println(s)
}
}
func DoIt() {
things := []any{"foo", 1, true, 6.4}
for _, t := range things {
Execute(t)
}
}