types

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

A handful of examples using the standard builtin types.

Example (StructsBasic)

ExampleStructs illustrates creating a simple struct.

package main

import (
	"fmt"
)

func main() {
	type contact struct {
		firstName string
		lastName  string
	}

	friends := []contact{
		{
			firstName: "John",
			lastName:  "Smith",
		},
		{
			"Jane",
			"Doe",
		},
	}

	for i, v := range friends {
		fmt.Printf("%02d: %s, %s\n", i, v.lastName, v.firstName)
	}
}
Output:

00: Smith, John
01: Doe, Jane
Example (StructsComposedFields)
package main

import (
	"fmt"
)

func main() {
	type contact struct {
		firstName string
		lastName  string
	}

	type friend struct {
		contact
		circle string
	}

	friends := []friend{
		{
			contact: contact{
				firstName: "John",
				lastName:  "Smith",
			},
			circle: "school",
		},
		{
			contact{
				"Jane",
				"Doe",
			},
			"work",
		},
	}

	for i, v := range friends {
		fmt.Printf("%02d: %6s %s, %s\n", i, v.circle, v.lastName, v.firstName)
	}
}
Output:

00: school Smith, John
01:   work Doe, Jane
Example (StructsComposedMethods)
package main

import "fmt"

type contact struct {
	firstName string
	lastName  string
}

type friend struct {
	contact
	circle string
}

func (c contact) fullName() string {
	return c.firstName + " " + c.lastName
}

func (f friend) summary() string {
	return fmt.Sprintf("%s %s", f.circle, f.fullName())
}

func main() {
	friends := []friend{
		{
			contact: contact{
				firstName: "John",
				lastName:  "Smith",
			},
			circle: "school",
		},
		{
			contact{
				"Jane",
				"Doe",
			},
			"work",
		},
	}

	for i, f := range friends {
		fmt.Printf("%02d:\n", i)
		fmt.Printf("   %s\n", f.summary())
		fmt.Printf("   %s %s\n", f.circle, f.fullName())
		fmt.Printf("   %s %s %s\n", f.circle, f.firstName, f.lastName)
	}
}
Output:

00:
   school John Smith
   school John Smith
   school John Smith
01:
   work Jane Doe
   work Jane Doe
   work Jane Doe

Jump to

Keyboard shortcuts

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