Created
January 17, 2018 12:57
-
-
Save deividaspetraitis/bebb6313094a7f6789e2c7edbe9ed846 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"encoding/json" | |
"reflect" | |
) | |
type circle struct { | |
Radius float64 `json:"radius"` | |
} | |
type square struct { | |
Edge float64 `json:"edge"` | |
} | |
func (c square) area() float64 { | |
return c.Edge * c.Edge | |
} | |
type shape interface { | |
area() float64 | |
} | |
func (c circle) area() float64 { | |
return 3.14 * c.Radius * c.Radius | |
} | |
func info(s shape) { | |
fmt.Println("area", s.area()) | |
} | |
func getType(myvar interface{}) string { | |
if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr { | |
return "*" + t.Elem().Name() | |
} else { | |
return t.Name() | |
} | |
} | |
func main() { | |
js1 := []byte(`{"radius": 2.32}`) | |
js2 := []byte(`{"edge": 1.2}`) | |
c := circle{} | |
s := square{} | |
json.Unmarshal(js1, &c) | |
json.Unmarshal(js2, &s) | |
// c - 16.900736 | |
// s - 1.44 | |
fmt.Println(c.area(), s.area()) | |
// What about: | |
// Works fine | |
var i shape | |
i = circle{1.2} | |
info(i) | |
// Not working.. | |
var i2 shape // <-- nil | |
i2 = circle{} | |
// It should be no more empty interface, Circle struct instead! | |
fmt.Println(getType(i2)) // <-- Yep, It's circle! | |
// QUESTION 1: This will not assign values, but why, because it's interface? | |
// Fields are not accessible only methods circle.area() ! | |
// QUESTION 2: How to assign values from JSON string to such struct`s? | |
json.Unmarshal(js1, &i2) | |
info(i2) // out: area 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer: