constiota

Rust Example from source

// Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.
// Each is different and independent.
enum WebEvent {
    // An `enum` variant may either be `unit-like`,
    PageLoad,
    PageUnload,
    // like tuple structs,
    KeyPress(char),
    Paste(String),
    // or c-like structures.
    Click { x: i64, y: i64 },
}

// A function which takes a `WebEvent` enum as an argument and
// returns nothing.
fn inspect(event: WebEvent) {
    match event {
        WebEvent::PageLoad => println!("page loaded"),
        WebEvent::PageUnload => println!("page unloaded"),
        // Destructure `c` from inside the `enum` variant.
        WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
        WebEvent::Paste(s) => println!("pasted \"{}\".", s),
        // Destructure `Click` into `x` and `y`.
        WebEvent::Click { x, y } => {
            println!("clicked at x={}, y={}.", x, y);
        },
    }
}

fn main() {
    let pressed = WebEvent::KeyPress('x');
    // `to_owned()` creates an owned `String` from a string slice.
    let pasted  = WebEvent::Paste("my text".to_owned());
    let click   = WebEvent::Click { x: 20, y: 80 };
    let load    = WebEvent::PageLoad;
    let unload  = WebEvent::PageUnload;

    inspect(pressed);
    inspect(pasted);
    inspect(click);
    inspect(load);
    inspect(unload);
}

structWebEvent
package main

import "fmt"

type PageStatus int

const (
    PAGELOAD PageStatus = iota
    PAGEUNLOAD
)

type WebEvent interface{}

type PageLoad struct {
    WebEvent
    status PageStatus
}
type PageUnload struct {
    WebEvent
    status PageStatus
}

type KeyPress struct {
    WebEvent
    key string
}

type Paste struct {
    WebEvent
    text string
}

type Click struct {
    WebEvent
    x, y int
}

func inspect(event WebEvent) {
    switch event.(type) {

    case PageLoad:
        fmt.Println("page loaded")

    case PageUnload:
        fmt.Println("page unloaded")

    case KeyPress:
        fmt.Println("pressed %v", event.key)

    case Paste:
        fmt.Println("pasted: %v", event.text)

    case Click:
        fmt.Println("clicked at x: %v, y:%v", event.x, event.y)

    default:
        fmt.Println("Event not recognized")
    }
}
func main() {
    pressed := KeyPress{key: "x"}
    pasted := Paste{text: "my text"}
    click := Click{x: 20, y: 80}
    load := PageLoad{status: PAGELOAD}
    unload := PageUnload{status: PAGEUNLOAD}

    inspect(pressed)
    inspect(pasted)
    inspect(click)
    inspect(load)
    inspect(unload)
}

(KeyPress)(event)