Skip to content

Added NormalizedString to be used as key in maps #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 16, 2023
Merged

Conversation

cmaglie
Copy link
Member

@cmaglie cmaglie commented Mar 15, 2023

Sometimes it's useful to have a map like map[string]*Release that maps a version to the corresponding release. Anyway, this has a drawback, if the version is not normalized before being assigned as a key we may end up having something like:

"1.0": &Release{...},
"1.0.0": &Release{...},

where two different entries are present for the same version.
To avoid this kind of problem this PR adds a new type NormalizedString, so the previous map can be rewritten as map[semver.NormalizedString]*Release. To obtain the normalized string the method Version.NormalizedString() can be used.

releases := map[semver.NormalizedString]*Release{}

v10 := semver.MustParse("1.0")
releases[v10.NormalizedString()] = release1

v100 := semver.MustParse("1.0.0")
releases[v100.NormalizedString()] = release2  // replaces "release1"

r := releases[v10.NormalizedString()] // gets "release2"
fmt.Println(v10.Equal(v100)) // prints "true"

it also helps with a compile-time sanity check on code doing the wrong thing:

releases[v10.String()] = release1
// error: cannot use v10.String() (value of type string) as semver.NormalizedString value in map

@cmaglie cmaglie self-assigned this Mar 15, 2023
@cmaglie cmaglie added the enhancement New feature or request label Mar 15, 2023
@codecov
Copy link

codecov bot commented Mar 15, 2023

Codecov Report

Merging #12 (9dd7f57) into master (518e126) will not change coverage.
The diff coverage is 100.00%.

@@            Coverage Diff            @@
##            master       #12   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           10        10           
  Lines          761       804   +43     
=========================================
+ Hits           761       804   +43     
Impacted Files Coverage Δ
relaxed_version.go 100.00% <100.00%> (ø)
version.go 100.00% <100.00%> (ø)

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@cmaglie cmaglie merged commit e797f1e into master Mar 16, 2023
@cmaglie cmaglie deleted the normalized_string branch March 16, 2023 14:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants