Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As <a href="https://stackoverflow.com/a/19374861/1567738">mentioned by ANisus</a>, different approaches will suit different sizes of input slices. This solution will work in linear time <code>O(n)</code> independent of input size, but assumes that the "equality" includes index position.</p> <p>Thus, in the OP's examples of:</p> <pre><code>slice1 := []string{"foo", "bar","hello"} slice2 := []string{"foo", "bar"} </code></pre> <p>The entries <code>foo</code> and <code>bar</code> are equal not just due to value, but also due to their index in the slice.</p> <p>Given these conditions, you can do something like:</p> <pre><code>package main import "fmt" func difference(s1, s2 []string) string { var ( lenMin int longest []string out string ) // Determine the shortest length and the longest slice if len(s1) &lt; len(s2) { lenMin = len(s1) longest = s2 } else { lenMin = len(s2) longest = s1 } // compare common indeces for i := 0; i &lt; lenMin; i++ { if s1[i] != s2[i] { out += fmt.Sprintf("=&gt;\t%s\t%s\n", s1[i], s2[i]) } } // add indeces not in common for _, v := range longest[lenMin:] { out += fmt.Sprintf("=&gt;\t%s\n", v) } return out } func main() { slice1 := []string{"foo", "bar", "hello"} slice2 := []string{"foo", "bar"} fmt.Print(difference(slice1, slice2)) } </code></pre> <p>Produces:</p> <blockquote> <blockquote> <p>=> hello</p> </blockquote> </blockquote> <p><a href="http://play.golang.org/p/tAEmJvpGp5" rel="nofollow noreferrer">Playground</a></p> <p>If you change the slices to be:</p> <pre><code>func main() { slice1 := []string{"foo", "baz", "hello"} slice2 := []string{"foo", "bar"} fmt.Print(difference(slice1, slice2)) } </code></pre> <p>It will produce:</p> <blockquote> <blockquote> <p>=> baz bar<br> => hello</p> </blockquote> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload