<p><a href="https://play.golang.org/p/wpcFO8SjDq">https://play.golang.org/p/wpcFO8SjDq</a></p>
<p>I'm trying to sort a slice, but relevant sort field has some sentinel data (in this case -1) that I want to sort to the end of the list, instead of it's natural order. Can anyone look at the playground example above and get the sort to work, but with values of -1 at the end of the list?</p>
<hr/>**评论:**<br/><br/>_nefario_: <pre><p>if you need -1 to be at the end, the Less func should have a special rule for that value to override the comparison</p>
<p>example:
<a href="https://play.golang.org/p/5UNxnIKDHw" rel="nofollow">https://play.golang.org/p/5UNxnIKDHw</a></p></pre>caseynashvegas: <pre><p>Thanks, that's golden, I was only thinking about checking the i side, not both. </p></pre>element131: <pre><p><a href="https://play.golang.org/p/ThqpRp3IGT" rel="nofollow">https://play.golang.org/p/ThqpRp3IGT</a></p>
<pre><code>sort.Slice(data, func(i, j int) bool {
return data[i].Value < data[j].Value || (data[j].Value == -1)
});
</code></pre></pre>caseynashvegas: <pre><p>I think this is the best answer, are there any use cases it misses?</p></pre>nsd433: <pre><p>What about putting the -1 at the end to start with and calling
sort.Sort(slice[0:len(slice)-1])</p>
<p>That won't move the -1 since it doesn't know about it.</p></pre>caseynashvegas: <pre><p>I'm not one to complain, but why did someone down vote this question? Seems shitty to down vote a legitimate question with an example on the playground. And at least to me, the answer was non obvious. If you're going to down vote you should at least comment as to why in my opinion.</p></pre>very-little-gravitas: <pre><p>You can also use sort.SliceStable to combine several sort criteria</p>
<p><a href="https://play.golang.org/p/qeJhbexl33" rel="nofollow">https://play.golang.org/p/qeJhbexl33</a></p></pre>