Free AI web copilot to create summaries, insights and extended knowledge, download it at here
1161
Abstract
ke any number of trailing arguments. Create a variadic function by prefixing the type with <code>...</code> like this:</p><div id="2bcf"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sum</span><span class="hljs-params">(nums ...<span class="hljs-type">int</span>)</span></span> <span class="hljs-type">int</span> {
total := <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> _, num := <span class="hljs-keyword">range</span> nums {
total += num
}
<span class="hljs-keyword">return</span> total
}</pre></div><p id="b14b">In this example, nums will be a <code>slice</code> of <code>ints</code>. You would call <code>sum</code> like this:</p><div id="057f"><pre><span class="hljs-attribute">total</span> := sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">15</span>, <span class="hljs-number">24</span>)
<span class="hljs-attribute">fmt</span>.Println(total) // <span class="hljs-number">42</span></pre></div><p id="eaec">You can also use the <code>...</code> a notation to pass a <b>slice</b> (not an array) into a variadic f
Options
unction like this:</p><div id="bdcd"><pre><span class="hljs-built_in">slice</span> := []int{<span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">9</span>, <span class="hljs-number">8</span>}
total = <span class="hljs-built_in">sum</span>(<span class="hljs-built_in">slice</span>...)
fmt.Println(total) <span class="hljs-comment">// 24</span></pre></div><p id="1488"><a href="https://go.dev/play/p/e7m8J3pRRLi">Try it here</a></p><h2 id="1363">Wildcard for package lists</h2><p id="c38d">You’ll most likely have seen or used this command already:</p><div id="009e"><pre>go <span class="hljs-built_in">test</span> ./...</pre></div><p id="192c">It simply means “test all <b>packages</b> in this directory (and subdirectories)”</p><p id="504b">More <a href="https://richard-t-bell90.medium.com/list/golang-in-sixty-seconds-7a26c5131734">Golang in sixty seconds</a></p><p id="fcd1"><a href="https://richard-t-bell90.medium.com/membership"><i>Get Unlimited access to Medium</i></a></p><p id="cf40"><a href="https://ko-fi.com/richardtbell"><i>Buy me a coffee</i></a><i> if you enjoyed the article :)</i></p></article></body>