interfaces

package
v0.0.0-...-14c8dc9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 13, 2017 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Here are some contrived examples that show the use of interfaces.

Example (Interfaces)
package main

import "fmt"

type Modifier interface {
	Modify() string
}

func Apply(obj Modifier) string {
	return obj.Modify()
}

type Echoer struct {
	Message string
}

func (e Echoer) Modify() string {
	return e.Message
}

type Reverser struct {
	Message string
}

func (e Reverser) Modify() string {
	last := len(e.Message) - 1
	var output []byte
	for i, _ := range e.Message {
		output = append(output, e.Message[last-i])
	}
	return string(output)
}

func main() {
	fmt.Println(Apply(Echoer{"Hello"}))
	fmt.Println(Apply(Reverser{"Hello"}))
}
Output:

Hello
olleH

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL