Created
April 13, 2017 04:51
-
-
Save ederavilaprado/7b4857bd7daf4ff823b19a55a2343875 to your computer and use it in GitHub Desktop.
Go type assertion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "fmt" | |
| type Item interface{} | |
| type Product struct { | |
| ID int | |
| Name string | |
| } | |
| type CompleteProduct struct { | |
| Product | |
| Size int32 | |
| } | |
| func teste(input Item) { | |
| fmt.Printf("=> %+v\n", input) | |
| switch t := input.(type) { | |
| case Product: | |
| fmt.Printf("=> Product: %+v\n", t) | |
| case CompleteProduct: | |
| fmt.Printf("=> CompletedProduct: %+v\n", t) | |
| default: | |
| fmt.Printf("=> %+v\n", "ops") | |
| } | |
| } | |
| func main() { | |
| // product := Product{ | |
| // ID: 1, | |
| // Name: "So, ok" | |
| // } | |
| p := Product{} | |
| p.ID = 1 | |
| p.Name = "Teste for name" | |
| // p.Size = 33 | |
| fmt.Printf("=> %+v\n", p) | |
| teste(p) | |
| // item, ok := product.(interface) | |
| // fmt.Printf("=> ok: %+v\n", ok) | |
| // fmt.Printf("=> %+v\n", item) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment