github.com/teh-cmc/mmm@v0.0.0-20160717174312-f3d5d92d1c27/examples/simple.go (about)

     1  // Copyright © 2015 Clement 'cmc' Rey <cr.rey.clement@gmail.com>.
     2  //
     3  // Use of this source code is governed by an MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package main
     7  
     8  /////
     9  // Simple example of usage
    10  //
    11  //   go run examples/simple.go
    12  //
    13  /////
    14  
    15  import (
    16  	"fmt"
    17  	"log"
    18  	"unsafe"
    19  
    20  	"github.com/teh-cmc/mmm"
    21  )
    22  
    23  type Coordinate struct {
    24  	x, y int
    25  }
    26  
    27  func main() {
    28  	// create a new memory chunk that contains 3 Coordinate structures
    29  	mc, err := mmm.NewMemChunk(Coordinate{}, 3)
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  
    34  	// print 3
    35  	fmt.Println(mc.NbObjects())
    36  
    37  	// write {3,9} at index 0, then print {3,9}
    38  	fmt.Println(mc.Write(0, Coordinate{3, 9}))
    39  	// write {17,2} at index 1, then print {17,2}
    40  	fmt.Println(mc.Write(1, Coordinate{17, 2}))
    41  	// write {42,42} at index 2, then print {42,42}
    42  	fmt.Println(mc.Write(2, Coordinate{42, 42}))
    43  
    44  	// print {17,2}
    45  	fmt.Println(mc.Read(1))
    46  	// print {42,42}
    47  	fmt.Println(*((*Coordinate)(unsafe.Pointer(mc.Pointer(2)))))
    48  
    49  	// free memory chunk
    50  	if err := mc.Delete(); err != nil {
    51  		log.Fatal(err)
    52  	}
    53  }