Return Unique items in a Go slice

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?



// 
// Returns unique items in a slice
//
func Unique(strSlice string) string
keys := make(map[string]bool)
list := string
for _, entry := range strSlice
if _, value := keys[entry]; !value
keys[entry] = true
list = append(list, entry)


return list







share|improve this question

























    up vote
    2
    down vote

    favorite












    I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?



    // 
    // Returns unique items in a slice
    //
    func Unique(strSlice string) string
    keys := make(map[string]bool)
    list := string
    for _, entry := range strSlice
    if _, value := keys[entry]; !value
    keys[entry] = true
    list = append(list, entry)


    return list







    share|improve this question





















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?



      // 
      // Returns unique items in a slice
      //
      func Unique(strSlice string) string
      keys := make(map[string]bool)
      list := string
      for _, entry := range strSlice
      if _, value := keys[entry]; !value
      keys[entry] = true
      list = append(list, entry)


      return list







      share|improve this question











      I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?



      // 
      // Returns unique items in a slice
      //
      func Unique(strSlice string) string
      keys := make(map[string]bool)
      list := string
      for _, entry := range strSlice
      if _, value := keys[entry]; !value
      keys[entry] = true
      list = append(list, entry)


      return list









      share|improve this question










      share|improve this question




      share|improve this question









      asked Apr 4 at 11:12









      Codingo

      8422826




      8422826




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          This is not idiomatic writing style in Go, because the value variable is misleading:




          if _, value := keys[entry]; !value {



          The first returned value is the value in the map, the second value indicates success or failure of the lookup.
          So rename it to ok or found.



          If the slice is very large,
          then list = append(list, entry) may lead to repeated allocations.
          In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
          But if you have no reason for this optimization then don't do it,
          that would be premature optimization,
          the current solution is fine.






          share|improve this answer




























            up vote
            0
            down vote













            Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:



            //
            // Returns unique items in a slice
            //
            func Unique(slice string) string
            // create a map with all the values as key
            uniqMap := make(map[string]struct)
            for _, v := range slice
            uniqMap[v] = struct


            // turn the map keys into a slice
            uniqSlice := make(string, 0, len(uniqMap))
            for v := range uniqMap
            uniqSlice = append(uniqSlice, v)

            return uniqSlice



            If your are not interested into the value of the map, it is customary to store the empty struct.






            share|improve this answer





















              Your Answer




              StackExchange.ifUsing("editor", function ()
              return StackExchange.using("mathjaxEditing", function ()
              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
              );
              );
              , "mathjax-editing");

              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "196"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: false,
              noModals: false,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );








               

              draft saved


              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191238%2freturn-unique-items-in-a-go-slice%23new-answer', 'question_page');

              );

              Post as a guest






























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              3
              down vote



              accepted










              This is not idiomatic writing style in Go, because the value variable is misleading:




              if _, value := keys[entry]; !value {



              The first returned value is the value in the map, the second value indicates success or failure of the lookup.
              So rename it to ok or found.



              If the slice is very large,
              then list = append(list, entry) may lead to repeated allocations.
              In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
              But if you have no reason for this optimization then don't do it,
              that would be premature optimization,
              the current solution is fine.






              share|improve this answer

























                up vote
                3
                down vote



                accepted










                This is not idiomatic writing style in Go, because the value variable is misleading:




                if _, value := keys[entry]; !value {



                The first returned value is the value in the map, the second value indicates success or failure of the lookup.
                So rename it to ok or found.



                If the slice is very large,
                then list = append(list, entry) may lead to repeated allocations.
                In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
                But if you have no reason for this optimization then don't do it,
                that would be premature optimization,
                the current solution is fine.






                share|improve this answer























                  up vote
                  3
                  down vote



                  accepted







                  up vote
                  3
                  down vote



                  accepted






                  This is not idiomatic writing style in Go, because the value variable is misleading:




                  if _, value := keys[entry]; !value {



                  The first returned value is the value in the map, the second value indicates success or failure of the lookup.
                  So rename it to ok or found.



                  If the slice is very large,
                  then list = append(list, entry) may lead to repeated allocations.
                  In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
                  But if you have no reason for this optimization then don't do it,
                  that would be premature optimization,
                  the current solution is fine.






                  share|improve this answer













                  This is not idiomatic writing style in Go, because the value variable is misleading:




                  if _, value := keys[entry]; !value {



                  The first returned value is the value in the map, the second value indicates success or failure of the lookup.
                  So rename it to ok or found.



                  If the slice is very large,
                  then list = append(list, entry) may lead to repeated allocations.
                  In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append.
                  But if you have no reason for this optimization then don't do it,
                  that would be premature optimization,
                  the current solution is fine.







                  share|improve this answer













                  share|improve this answer



                  share|improve this answer











                  answered Apr 6 at 22:03









                  janos

                  95.5k12120343




                  95.5k12120343






















                      up vote
                      0
                      down vote













                      Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:



                      //
                      // Returns unique items in a slice
                      //
                      func Unique(slice string) string
                      // create a map with all the values as key
                      uniqMap := make(map[string]struct)
                      for _, v := range slice
                      uniqMap[v] = struct


                      // turn the map keys into a slice
                      uniqSlice := make(string, 0, len(uniqMap))
                      for v := range uniqMap
                      uniqSlice = append(uniqSlice, v)

                      return uniqSlice



                      If your are not interested into the value of the map, it is customary to store the empty struct.






                      share|improve this answer

























                        up vote
                        0
                        down vote













                        Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:



                        //
                        // Returns unique items in a slice
                        //
                        func Unique(slice string) string
                        // create a map with all the values as key
                        uniqMap := make(map[string]struct)
                        for _, v := range slice
                        uniqMap[v] = struct


                        // turn the map keys into a slice
                        uniqSlice := make(string, 0, len(uniqMap))
                        for v := range uniqMap
                        uniqSlice = append(uniqSlice, v)

                        return uniqSlice



                        If your are not interested into the value of the map, it is customary to store the empty struct.






                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:



                          //
                          // Returns unique items in a slice
                          //
                          func Unique(slice string) string
                          // create a map with all the values as key
                          uniqMap := make(map[string]struct)
                          for _, v := range slice
                          uniqMap[v] = struct


                          // turn the map keys into a slice
                          uniqSlice := make(string, 0, len(uniqMap))
                          for v := range uniqMap
                          uniqSlice = append(uniqSlice, v)

                          return uniqSlice



                          If your are not interested into the value of the map, it is customary to store the empty struct.






                          share|improve this answer













                          Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:



                          //
                          // Returns unique items in a slice
                          //
                          func Unique(slice string) string
                          // create a map with all the values as key
                          uniqMap := make(map[string]struct)
                          for _, v := range slice
                          uniqMap[v] = struct


                          // turn the map keys into a slice
                          uniqSlice := make(string, 0, len(uniqMap))
                          for v := range uniqMap
                          uniqSlice = append(uniqSlice, v)

                          return uniqSlice



                          If your are not interested into the value of the map, it is customary to store the empty struct.







                          share|improve this answer













                          share|improve this answer



                          share|improve this answer











                          answered Apr 25 at 21:52









                          oliverpool

                          1,542425




                          1,542425






















                               

                              draft saved


                              draft discarded


























                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191238%2freturn-unique-items-in-a-go-slice%23new-answer', 'question_page');

                              );

                              Post as a guest













































































                              Popular posts from this blog

                              Chat program with C++ and SFML

                              Function to Return a JSON Like Objects Using VBA Collections and Arrays

                              Will my employers contract hold up in court?