Commit 02a2872d authored by Boris Mühmer's avatar Boris Mühmer
Browse files

added basic interface example

parent cc7502ba
Loading
Loading
Loading
Loading
+70 −0
Original line number Diff line number Diff line
package interfaces

// S1 is an example structure.
type S1 struct {
	v1 int
}

// S2 is an example structure.
type S2 struct {
	v2 int
}

// S3 is an example structure.
type S3 struct {
	v3 int
}

// NewS1 creates a new instance.
func NewS1(v int) *S1 {
	return &S1{v1: v}
}

// Value implements the Valuer interface.
func (s *S1) Value() int {
	return s.v1
}

// SetValue implements the Valuer interface.
func (s *S1) SetValue(vn int) (vo int) {
	vo, s.v1 = s.v1, vn
	return
}

// NewS2 creates a new instance.
func NewS2(v int) *S2 {
	return &S2{v2: v}
}

// Value implements the Valuer interface.
func (s *S2) Value() int {
	return s.v2
}

// SetValue implements the Valuer interface.
func (s *S2) SetValue(vn int) (vo int) {
	vo, s.v2 = s.v2, vn
	return
}

// NewS3 creates a new instance.
func NewS3(v int) *S3 {
	return &S3{v3: v}
}

// Value implements the Valuer interface.
func (s *S3) Value() int {
	return s.v3
}

// SetValue implements the Valuer interface.
func (s *S3) SetValue(vn int) (vo int) {
	vo, s.v3 = s.v3, vn
	return
}

// Valuer provides accessor functions.
type Valuer interface {
	Value() int       // get current value
	SetValue(int) int // set new value, return old value
}
+25 −0
Original line number Diff line number Diff line
package interfaces

import "testing"

func TestInterfacesAssignment(t *testing.T) {
	vn := 42
	for _, v := range []struct {
		s Valuer
		r int
	}{
		{NewS1(1), 1},
		{NewS2(2), 2},
		{NewS3(3), 3},
	} {
		if r := v.s.Value(); r != v.r {
			t.Logf("%v.Value() is %d, expected %d", v.s, r, v.r)
		}
		if ov := v.s.SetValue(vn); ov != v.r {
			t.Logf("%v.Value() is %d, expected %d", v.s, ov, v.r)
		}
		if r := v.s.Value(); r != vn {
			t.Logf("%v.Value() is %d, expected %d", v.s, r, vn)
		}
	}
}