如何建立一套?

Given an array of float64 (or any other thing), I would like to build a set similar to the set we find in python. What is the best approach to designing such a data structure?

So far I managed to build a set using a map but it seems awkward to repurpose map to build a set.

package main

import (
    "fmt"
    "sort"
)

func main() {

    var scores = []float64{
        12.0, 6.0, 19.0, 20.0, 2.0, 8.0, 20.0,
    }

    set := make(map[float64]bool)
    for _, t := range scores {
        set[t] = true
    }

    unk := make([]float64, 0, len(set))
    for t := range set {
        unk = append(unk, t)
    }

    sort.Float64s(unk)
    fmt.Println(unk)
}

Will produce

[2 6 8 12 19 20]

Using a map[float64]bool (or map[float64]struct{}) works well unless you need to have NaNs in the set in which case it will fail.

Float sets need extra logic to handle the NaN case as NaNs can be used as map indices but do not work as expected.

You should define your own FloatSet which consists of two fields: One map[float64]struct{} for all "normal" floats (including the Infs) and one hasNaN bool field for NaNs. Insert, Lookup, Remove code need both an extra code path to handle NaNs.

The "happy" path is perfectly covered by icza's answer but floats always need special treatment for NaNs. (Unless your set will never contain NaNs, until it will contain a NaN and your code will fail with a hard to detect bug.)