Skip to content

Instantly share code, notes, and snippets.

@deividaspetraitis
Created January 17, 2018 12:57
Show Gist options
  • Save deividaspetraitis/bebb6313094a7f6789e2c7edbe9ed846 to your computer and use it in GitHub Desktop.
Save deividaspetraitis/bebb6313094a7f6789e2c7edbe9ed846 to your computer and use it in GitHub Desktop.
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
}
@deividaspetraitis
Copy link
Author

Answer:

	// Interface
	var i2 shape // <-- nil

	// Actual literal
	qc := circle{}

	// QUESTION 1:  This will not assign values, but why, because it's interface?
	// Fields are not accessible only methods circle.area() !
	// i2 - interface
	// qc - actual literal

	// QUESTION 2: How to assign values from JSON string to such struct`s?

	// Unmarshal to actual literal
	json.Unmarshal(js1, &qc)

	// Assign literal to interface
	i2 = qc

	info(i2) // out: area 16.900736

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment