Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Container types in Go

I am trying to familiarize myself with Go and so was trying to implements some search function but looking through the docs for the container types, none of the inbuilt type implements a contains method. Am i missing something and if not how do i go about testing for membership? Do I have to implement my own method or i have to iterate through all elements. If this is so what is the rationale behind the omission of this elementary method for container types?

like image 907
cobie Avatar asked Nov 23 '12 21:11

cobie


People also ask

What are go types?

Go has three basic data types: bool: represents a boolean value and is either true or false. Numeric: represents integer types, floating point values, and complex types. string: represents a string value.

What is container go?

It is like a multi tenancy where the Containers are shared through same host kernel but each of it has their own virtualized network adapter and filesystem. It allows to develop, deployment and management applications in efficient manner. Docker containers are developed using Go Language.

How do you declare types in Go?

The declaration starts with the keyword type, then a name for the new struct, and finally the keyword struct. Within the curly brackets, a series of data fields are specified with a name and a type.

What is difference between Array and slice in Golang?

Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.


2 Answers

The standard library's container types require you do type assertions when pulling elements out. The containers themselves have no way of doing tests for membership because they don't know the types they're containing and have no way of doing a comparison.

Ric Szopa's skip list implementation might be what you're looking for. It has a Set type which implements a Contains method.

https://github.com/ryszard/goskiplist

I've been using it in production and am quite happy with it.

like image 166
Daniel Avatar answered Oct 13 '22 21:10

Daniel


Maps are a built-in type which has a "contains" construct, not a method, though.

http://play.golang.org/p/ddpmiskxqS

package main

import (
    "fmt"
)

func main() {
    a := map[string]string{"foo": "bar"}
    _, k := a["asd"]
    fmt.Println(k)
    _, k = a["foo"]
    fmt.Println(k)
}
like image 35
thwd Avatar answered Oct 13 '22 21:10

thwd