Jump to content

Create an object/Native demonstration: Difference between revisions

Added Go
(Removed {{omit from|Go}} template as this task can in fact be completed in the language using a read-only wrapper for the map type.)
(Added Go)
Line 49:
55
["a":1, "b":66]</pre>
 
=={{header|Go}}==
Go's built-in map type is mutable and so, to complete this task, we need to create a read-only wrapper for it which doesn't permit further items to be added or existing items to be deleted though does allow them to be reset to their default value.
 
First create a sub-directory, romap, of the project directory and place the following package in it:
<lang go>package romap
 
type Romap struct{ imap map[byte]int }
 
// Create new read-only wrapper for the given map.
func New(m map[byte]int) *Romap {
if m == nil {
return nil
}
return &Romap{m}
}
 
// Retrieve value for a given key, if it exists.
func (rom *Romap) Get(key byte) (int, bool) {
i, ok := rom.imap[key]
return i, ok
}
 
// Reset value for a given key, if it exists.
func (rom *Romap) Reset(key byte) {
_, ok := rom.imap[key]
if ok {
rom.imap[key] = 0 // default value of int
}
}</lang>
 
This package can now be imported and used within the main package as follows:
<lang go>package main
 
import (
"./romap"
"fmt"
)
 
func main() {
// create a normal map
m := map[byte]int{'A': 65, 'B': 66, 'C': 67}
 
// place it in a read-only wrapper so no new item can be added or item deleted.
rom := romap.New(m)
 
// retrieve value represented by 'C' say
i, _ := rom.Get('C')
fmt.Println("'C' maps to", i)
 
// reset this to default value (doesn't actually delete the key)
rom.Reset('C')
i, _ = rom.Get('C')
fmt.Println("'C' now maps to", i)
}</lang>
 
{{out}}
<pre>
'C' maps to 67
'C' now maps to 0
</pre>
 
=={{header|J}}==
9,485

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.