Go, Rust Cheat Sheet 2
Go, Rust Cheat Sheet 2
Go, Rust Cheat Sheet 2
Programming-Idioms.org
Creative Commons Attribution-ShareAlike 3.0
fmt.Println(strings.Repeat("Hello\n", 1
0))
3 Create a procedure
Like a function which import "fmt" fn finish(name: &str) {
doesn't return any value,
println!("My job here is done. Good
thus has only side func finish(name string) { bye {}", name);
effects (e.g. Print to
fmt.Println("My job here is done. Goo }
standard output)
d bye " + name)
} The actual return type is Unit, typed '()' and can be omitted
from function signature.
There is no return type in the signature, before the { .
Alternative implementation:
import "fmt"
This is a closure.
Alternative implementation:
struct Point(f64, f64);
items.into_iter().for_each(|x| do_somet
hing(x));
7 Iterate over list indexes
and values import "fmt" for (i, x) in items.iter().enumerate()
Print each index i with its
{
value x from an array-
for i, x := range items { println!("Item {} = {}", i, x);
like collection items
fmt.Printf("Item %d = %v \n", i, x) }
}
The range clause gives you index i and value x at the same Alternative implementation:
time as loop variables items.iter().enumerate().for_each(|(i,
x)| {
println!("Item {} = {}", i, x);
})
Alternative implementation:
use std::collections::HashMap;
use rand::seq::SliceRandom;
Alternative implementation:
use rand::thread_rng;
import "math/rand"
let mut rng = thread_rng();
y := make([]T, len(x)) x.shuffle(&mut rng);
perm := rand.Perm(len(x))
for i, v := range perm { Requires the rand crate.
y[v] = x[i] (https://crates.io/crates/rand)
}
Alternative implementation:
import "math/rand"
Alternative implementation:
import "math/rand"
Alternative implementation:
import "math/rand"
Alternative implementation:
func pickT(x []T) T {
return x[rand.Intn(len(x))] use rand::seq::SliceRandom;
}
let mut rng = rand::thread_rng();
Without generics: if you decide to implement pickT, you will let choice = x.choose(&mut rng).unwrap
have to write it separately for each desired type T. ();
Alternative implementation: The choose method returns an Option which is None if x is
func pick[T any](x []T) T { empty.
return x[rand.Intn(len(x))]
}
slices.Contains(list, x) list.binary_search(&x).is_ok()
This generic func slices.Contains works for all slice types The list must be sorted!
Do not rely on the order of the traversal ! The order is You can also print collections in a 'nice' way with `println!("
undefined and is intentionaly randomized by the Go runtime. {:?}", mymap);` which is the Debug-representation. You can
also use "{:#?}" for the pretty version.
Alternative implementation:
use rand::distributions::Distributio
n;
use rand::distributions::Uniform;
Uniform::new_inclusive(a, b).sample(&mu
t rand::thread_rng())
16 Depth-first traversal of
a binary tree
func (bt *BinTree) Dfs(f func(*BinTre struct BiTree<T> {
Call a function f on every
e)) { left: Option<Box<BiTree<T>>>,
node of binary tree bt, in
if bt == nil { right: Option<Box<BiTree<T>>>,
depth-first infix order
return value: T,
} }
bt.Left.Dfs(f)
f(bt) fn depthFirstTraverse<T>(bt: &mut BiTre
bt.Right.Dfs(f) e<T>, f: fn(&mut BiTree<T>)) {
} if let Some(left) = &mut bt.left {
f(left);
The function f is a parameter of the traversal method Dfs. }
It's legit to call a method on a nil receiver, and useful to
make code more concise with less checks for nil. f(bt);
Alternative implementation:
if let Some(right) = &mut bt.right
func (bt *BinTree[L]) Dfs(f func(*BinTr {
ee[L])) { f(right);
if bt == nil { }
return }
}
bt.Left.Dfs(f)
f(bt)
bt.Right.Dfs(f)
}
Alternative implementation:
It operates in-place.
20 Return two values
Implement a function
func search(m [][]int, x int) (bool, in fn search<T: Eq>(m: &Vec<Vec<T>>, x: &
t, int) { T) -> Option<(usize, usize)> {
search which looks for
for i := range m { for (i, row) in m.iter().enumerate
item x in a 2D matrix m.
Return indices i, j of the
for j, v := range m[i] () {
{ for (j, column) in row.iter().e
matching cell.
Think of the most
if v == x { numerate() {
idiomatic way in the
return if *column == *x {
true, i, j return Some((i, j));
language to return the
two values at the same
} }
} }
time.
} }
return false, 0, 0
} None
}
Go functions may return multiple values.
This function returns 3 values : one to indicate if x was This returns an optional tuple.
found or not, and two for the coordinates.
21 Swap values
Swap the values of the
a, b = b, a std::mem::swap(&mut a, &mut b);
variables a and b
Alternative implementation:
i, err := strconv.ParseInt(s, 10, 0) This explicitly sets the value to 0 if it can't be parsed to an
integer.
Radix 10. The third argument 0 means "fit in
Alternative implementation:
implementation-specific int". But the result type is always
int64. let i = match s.parse::<i32>() {
Don't ignore the potential error err ! Ok(i) => i,
Err(_e) => -1,
};
x := make([][]float64, m)
for i := range x {
x[i] = buf[:n:n]
buf = buf[n:]
}
return x
}
Alternative implementation:
x := make([][]T, m)
for i := range x {
x[i] = buf[:n:n]
buf = buf[n:]
}
return x
}
Alternative implementation:
x := make([][][]T, m)
for i := range x {
x[i] = make([][]T, n)
for j := range x[i] {
x[i][j] = buf[:
p:p]
buf = buf[p:]
}
}
return x
}
Alternative implementation:
import "sort"
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
(0..1000).into_par_iter().for_each(f);
Alternative implementation:
Alternative implementation:
x := make(map[T]struct{})
Alternative implementation:
36 First-class function :
generic composition
func composeIntFuncs(f func(int) int, g fn compose<'a, A, B, C, G, F>(f: F, g:
Implement a function
func(int) int) func(int) int { G) -> Box<Fn(A) -> C + 'a>
compose which returns
return func(x int) int { where F: 'a + Fn(A) -> B, G: 'a
composition function g ∘
return g(f(x)) + Fn(B) -> C
f for any functions f and
} {
g having exactly 1
} Box::new(move |x| g(f(x)))
parameter.
}
These specific functions take and return concrete types.
Unfortunately, you'll need to implement another two variants
It could be done with an empty interface, but that would if you care about FnMut and FnOnce. Also, for now, you
discard static type checks (the implementations of f and g need to box the returned function. In the future, this
can still be type-checked, though). shouldn't be necessary.
use substring::Substring;
39 Check if string
contains a word import "strings" let ok = s.contains(word);
Set the boolean ok to
ok := strings.Contains(s, word)
true if the string word is
contained in string s as a
substring, or to false
otherwise.
40 Graph with adjacency
lists
type Vertex struct{
Id int
Declare a Graph data
structure in which each
Label string
Vertex has a collection
Neighbours map[*Vertex]bool
}
of its neighbouring
vertices.
type Graph []*Vertex
Alternative implementation:
import (
"strings"
"unicode/utf8"
)
Alternative implementation:
import "golang.org/x/exp/slices"
s = slices.Insert(s, i, x)
Alternative implementation:
let t = s.chars().take(5).collect::<Str
ing>();
let s = r#"Huey
Dewey
Louie"#;
Alternative implementation:
s := strconv.FormatInt(i, 10)
Alternative implementation:
import "fmt"
s := fmt.Sprintf("%d", i)
Alternative implementation:
n := 0
for _, v := range x {
if p(v) {
n++
}
}
y := make([]T, 0, n)
for _, v := range x {
if p(v) {
y = append(y, v)
}
}
Alternative implementation:
Alternative implementation:
use std::env;
let x = env::args().nth(1).unwrap_or
("".to_string());
Alternative implementation:
use std::time::SystemTime;
let d = SystemTime::now();
68 Create a bitset
Create an object x to import "math/big" let mut x = vec![false; n];
store n bits (n being
potentially large).
var x *big.Int = new(big.Int)
Alternative implementation:
x := make([]bool, n)
Alternative implementation:
x := make([]uint64, (n+63)/64)
r is of type *rand.Rand.
71 Echo program
implementation import "fmt" use std::env;
Basic implementation of import "os"
the Echo program: Print import "strings" println!("{}", env::args().skip(1).coll
all arguments except the
ect::<Vec<_>>().join(" "));
program name, func main() {
separated by space, fmt.Println(strings.Join(os.Args
Alternative implementation:
followed by newline. [1:], " "))
The idiom demonstrates
} use itertools::Itertools;
how to skip the first
println!("{}", std::env::args().skip
argument if necessary,
(1).format(" "));
concatenate arguments
as strings, append
newline and print it to
stdout.
73 Create a factory
Create a factory named
type ParentFactory func(string) Parent use core::fmt::Debug;
fact for any sub class of use std::str::FromStr;
Parent and taking var fact ParentFactory = func(str strin
exactly one string str as g) Parent { fn fact<Parent: std::str::FromStr>(str:
constructor parameter. return Parent{ String, _: Parent) -> Parent where <Par
name: str, ent as FromStr>::Err: Debug
} {
} return str.parse::<Parent>().unwrap
();
A Factory is a function which returns an object. }
import "fmt"
import "math/big"
s := fmt.Sprintf("%b", x)
Go has no do while loop, use the for loop, instead. Alternative implementation:
while {
Alternative implementation:
doStuff();
for done := false; !done; { c
someThing() } { /* EMPTY */ }
someOtherThing()
done = !c() Use compound expression for the while loop condition.
}
Alternative implementation:
import "math/bits"
c := bits.OnesCount(i)
i is a uint.
All OnesCountX functions take unsigned integer types.
85 Check if integer
addition will overflow import "math" fn adding_will_overflow(x: usize, y: us
Write boolean function
ize) -> bool {
addingWillOverflow
func addingWillOverflow(x int, y int) b x.checked_add(y).is_none()
which takes two integers ool { }
x, y and return true if if x > 0 {
return y > math.MaxInt- checked_add is available for all integer types.
(x+y) overflows.
x
An overflow may be
}
above the max positive
return y < math.MinInt-x
value, or below the min
}
negative value.
86 Check if integer
multiplication will func multiplyWillOverflow(x, y uint64) fn multiply_will_overflow(x: i64, y: i6
overflow
bool { 4) -> bool {
Write boolean function
if x <= 1 || y <= 1 { x.checked_mul(y).is_none()
multiplyWillOverflow
return false }
which takes two integers }
d := x * y checked_mul is available on all integer types
x, y and return true if
(x*y) overflows. return d/y != x
}
An overflow may be
This holds for uint64, not for signed integers.
above the max positive
Note that the multiplication is performed, then its result is
value, or below the min
checked.
negative value.
87 Stop program
Exit immediately. import "os" std::process::exit(0);
If some extra cleanup
os.Exit(0) No destructors on the current stack or any other thread's
work is executed by the
stack will be run.
program runtime (not by
the OS itself), describe
it.
88 Allocate 1M bytes
Create a new bytes
buf := make([]byte, 1_000_000) let buf: Vec<u8> = Vec::with_capacity(1
buffer buf of size
000000);
This creates a slice with all values initialized at zero.
1,000,000.
This creates a simple but fast vector. There is also the
unstable alloc::heap::allocate if you want to go more low-
level.
89 Handle invalid
argument
return nil, fmt.Errorf("invalid value f enum CustomError { InvalidAnswer }
You've detected that the
or x: %v", x)
integer value of
fn do_stuff(x: i32) -> Result<i32, Cust
The last return parameter of the current function has type omError> {
argument x passed to error.
the current function is
if x != 42 {
It is the caller's responsibility to check if the error is nil, Err(CustomError::InvalidAnswer)
invalid. Write the
before using the function's other result values. } else {
idiomatic way to abort
the function execution
Ok(x)
and signal the problem.
}
}
A function that can have invalid inputs should not panic, but
return a Result. The calling function can then determine
whether to handle the Err value or unwrap the Result and
turn every Err into a panic.
90 Read-only outside
Expose a read-only
type Foo struct { struct Foo {
integer x to the outside
x int x: usize
world while being
} }
writable inside a
structure or a class Foo. func (f *Foo) X() int { impl Foo {
return f.x pub fn new(x: usize) -> Self {
} Foo { x }
}
x is private, because it is not capitalized.
(*Foo).X is a public getter (a read accessor). pub fn x<'a>(&'a self) -> &'a usize
{
&self.x
}
buffer is a []byte.
&x is the address of x.
You must check errors after each step.
Alternative implementation:
import "encoding/json"
r, err := os.Open(filename)
if err != nil {
return err
}
decoder := json.NewDecoder(r)
err = decoder.Decode(&x)
if err != nil {
return err
}
use time::macros::format_description;
Alternative implementation:
import "sort"
Alternative implementation:
import "sort"
Alternative implementation:
import "golang.org/x/exp/slices"
slices.SortFunc(items, c)
use error_chain::error_chain;
use std::io::Read;
buffer is a []byte.
&x is the address of x.
You must check errors after each step.
104 Save object into XML
file import "encoding/xml"
Write the contents of the import "os"
object x into the file
data.xml.
buffer, err := xml.MarshalIndent(x, "",
" ")
if err != nil {
return err
}
err = os.WriteFile("data.xml", buffer,
0644)
Alternative implementation:
use std::process::Command;
Alternative implementation:
use std::process::Command;
Alternative implementation:
import "fmt"
import "golang.org/x/exp/maps"
import "golang.org/x/exp/slices"
keys := maps.Keys(mymap)
slices.Sort(keys)
Alternative implementation:
import "fmt"
import "golang.org/x/exp/maps"
import "golang.org/x/exp/slices"
keys := maps.Keys(mymap)
slices.SortFunc(keys, less)
Alternative implementation:
import "fmt"
import "sort"
Alternative implementation:
import "strings"
s2 := strings.ReplaceAll(s1, w, "")
Alternative implementation:
func sliceToSet[T comparable](x []T) ma
p[T]struct{} {
y := make(map[T]struct{}, len
(x))
for _, v := range x {
y[v] = struct{}{}
}
return y
}
This is O(n).
Alternative implementation:
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
x = x[:j]
This is O(n).
Alternative implementation:
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
for i := j; i < len(x); i++ {
x[i] = nil
}
x = x[:j]
Order is preserved.
Use this if T is a pointer type or reference type.
Discarded slots are set to nil, to avoid a memory leak.
This is O(n).
Alternative implementation:
func deduplicate[S ~[]T, T comparable]
(x S) S {
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
}
}
var zero T
for i := j; i < len(x); i++ {
// Avoid memory leak
x[i] = zero
}
return x[:j]
}
_, err := fmt.Scanf("%d", &n) Change i64 to what you expect to get. Do not use unwrap()
if you're not sure it will be parsed correctly.
Alternative implementation:
use std::io;
Alternative implementation:
use std::io::BufRead;
Alternative implementation:
Can also parse several values and types and delimiters with
scan!()
122 Declare an
enumeration
type Suit int enum Suit {
Spades,
Create an enumerated
type Suit with 4 possible
const ( Hearts,
values SPADES,
Spades Suit = iota Diamonds,
HEARTS, DIAMONDS,
Hearts Clubs,
CLUBS.
Diamonds }
Clubs
)
Iterative algorithm.
It does not always return the smallest possible index.
You may implement this for any element type T that is
ordered.
Alternative implementation:
import "sort"
Alternative implementation:
import "sort"
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
import "time"
t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)
let re =
RegexBuilder::new(®ex::escape(wo
rd))
.case_insensitive(true)
.build().unwrap();
let ok = re.is_match(s);
Alternative implementation:
let ok = s.to_ascii_lowercase().contain
s(&word.to_ascii_lowercase());
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
j := 0
for i, v := range items {
if v != x {
items[j] = items[i]
j++
}
}
items = items[:j]
Alternative implementation:
j := 0
for i, v := range items {
if v != x {
items[j] = items[i]
j++
}
}
for k := j; k < len(items); k++ {
items[k] = nil
}
items = items[:j]
Alternative implementation:
import "fmt"
E.g. 999 -> "3e7"
import "math/big"
s := fmt.Sprintf("%x", x)
import (
"fmt"
"strings"
"unicode"
)
import "strconv"
t := s + strconv.Itoa(i)
c := fmt.Sprintf("#%02X%02X%02X", r, g,
b)
Alternative implementation:
import "fmt"
import "strconv"
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg
-open", url).Start()
case "windows":
err = exec.Command("run
dll32", "url.dll,FileProtocolHandler",
url).Start()
case "darwin":
err = exec.Command("ope
n", url).Start()
default:
err = fmt.Errorf("unsup
ported platform")
}
if err != nil {
log.Fatal(err)
}
}
165 Last element of list
Assign to the variable x x := items[len(items)-1] let x = items[items.len()-1];
the last element of the
items is a slice.
list items. Alternative implementation:
There is no shortcut, use len!
Panics if the list is empty. let x = items.last().unwrap();
x is a Vec.
last() returns an Option<&T>.
166 Concatenate two lists
Create the list ab
ab := append(a, b...) let ab = [a, b].concat();
containing all the Warning! a and ab may or may not share the same
elements of the list a, underlying memory.
followed by all the
elements of the list b. Alternative implementation:
var ab []T
ab = append(append(ab, a...), b...)
Alternative implementation:
ab := make([]T, len(a)+len(b))
copy(ab, a)
copy(ab[len(a):], b)
Alternative implementation:
Alternative implementation:
let t = s.strip_prefix(p).unwrap_or(s);
let t = s.strip_suffix(w).unwrap_or(s);
Alternative implementation:
import "github.com/floscodes/golang-t
housands"
import "strconv"
n := strconv.Itoa(23489)
s := thousands.Separate(n, "en")
formValues has type net/url.Values The [dependencies] section goes to cargo.toml. The
optional feature blocking must be explicit.
Alternative implementation:
use data_encoding::HEXLOWER;
let s = HEXLOWER.encode(&a);
176 Hex string to byte
array import "encoding/hex" use hex::FromHex;
From hex string s of 2n
digits, build the a, err := hex.DecodeString(s) let a: Vec<u8> = Vec::from_hex(s).expec
equivalent array a of n if err != nil { t("Invalid Hex String");
bytes. log.Fatal(err)
Each pair of }
Alternative implementation:
hexadecimal characters
(16 possible values per
use hex::decode;
digit) is decoded into one
let a: Vec<u8> = decode(s).expect("Hex
byte (256 possible
string should be valid");
values).
Alternative implementation:
use data_encoding::HEXLOWER_PERMISSIV
E;
impl Rectangle {
pub fn center(&self) -> (f64, f64)
{
((self.x1 + self.x2) / 2.0,
(self.y1 + self.y2) / 2.0)
}
}
Alternative implementation:
import "time"
go func() {
time.Sleep(30 * time.Second)
f(42)
}()
Alternative implementation:
import "os"
defer os.Exit(0)
0.785 2
205 Get an environment
variable import "os" use std::env;
Read an environment
variable with the name
foo, ok := os.LookupEnv("FOO") let foo = match env::var("FOO") {
"FOO" and assign it to if !ok { Ok(val) => val,
the string variable foo. If
foo = "none" Err(_e) => "none".to_string(),
it does not exist or if the } };
system does not support
environment variables, Alternative implementation: Alternative implementation:
assign a value of "none".
import "os" use std::env;
Alternative implementation:
use std::env;
Example output:
This works only if path's parent already exists. This doesn't create parent directories. fs::create_dir_all
does.
Alternative implementation:
Alternative implementation:
import "os"
use std::fs;
err := os.MkdirAll(path, os.ModeDir)
fs::create_dir_all(path)?;
MkdirAll creates any necessary parents.
create_dir_all creates intermediate parent folders as
needed
212 Check if folder exists
Set the boolean b to import "os" use std::path::Path;
true if path exists on the
info, err := os.Stat(path) let b: bool = Path::new(path).is_dir();
filesystem and is a
b := !os.IsNotExist(err) && info.IsDir
directory; false
otherwise.
()
213 Case-insensitive string
compare use itertools::Itertools;
Compare four strings in
pair-wise variations. The
for x in strings
string comparison can .iter()
be implemented with an .combinations(2)
equality test or a .filter(|x| x[0].to_lowercase() ==
containment test, must x[1].to_lowercase())
be case-insensitive and
{
must apply Unicode println!("{:?} == {:?}", x[0], x
casefolding.
[1])
}
Alternative implementation:
var c S
for x := range seta {
if setb[x] {
c = append(c,
x)
}
}
return c
}
Alternative implementation:
func intersection[S ~[]T, T comparable]
(a, b S) S {
s, l := a, b
if len(b) < len(a) {
s, l = b, a
}
c := make(S, 0, len(s))
for _, x := range l {
if _, found := set[x];
found {
c = append(c,
x)
delete(set, x)
}
}
return c
}
Alternative implementation:
This generic func slices.Index works for all slice types Alternative implementation:
let i = items.iter().position(|y| *y ==
x).map_or(-1, |n| n as i32);
Alternative implementation:
items
.iter()
.find(|&&item| item == "rockstar pr
ogrammer")
.or_else(|| {
println!("NotFound");
Some(&"rockstar programmer")
});
Alternative implementation:
if 'search: loop {
for i in items {
if i == &"qux" {
println!("found it");
break 'search false;
}
}
break 'search true
} {
println!("not found!");
}
Alternative implementation:
'label: {
for &item in items {
if item == "baz" {
println!("foun
d");
break 'label;
}
}
println!("not found");
}
items = append(items, x)
copy(items[1:], items)
items[0] = x
Alternative implementation:
Alternative implementation:
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
import "os"
Alternative implementation:
import "io"
import "os"
func copy(dst, src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return err
}
g, err := os.OpenFile(dst, os.O
_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mo
de())
if err != nil {
return err
}
defer g.Close()
_, err = io.Copy(g, f)
if err != nil {
return err
}
return os.Chmod(dst, stat.Mode
())
}
somethingElse()
cancel()
Alternative implementation:
import "math/big"
q := new(big.Rat)
q.SetFrac(a, b)
Alternative implementation:
import "math/big"
q := big.NewRat(a, b)
Alternative implementation:
import "math/big"
c := new(big.Int)
c.Xor(a, b)
var c T
for i := range a {
c[i] = a[i] ^ b[i]
}
sort.Sort(&sorter{
k: a,
t: b,
})
x is a HashSet
243 Print list
Print the contents of the import "fmt" println!("{:?}", a)
list or array a on the a is a Vec.
standard output. fmt.Println(a)
Vec<T> doesn't implement the Display trait, however it
a is a slice. implements the Debug trait.
This works fine for simple types and structs.
It won't dereference pointers.
244 Print a map
import "fmt" println!("{:?}", m);
Print the contents of the
map m to the standard
fmt.Println(m)
output: keys and values.
This works fine for simple types of keys and values.
It won't dereference pointers.
Alternative implementation:
import "fmt"
fmt.Printf("%q", m)
Alternative implementation:
j := 0
for i, v := range x {
if p(v) {
x[j] = x[i]
j++
}
}
for k := j; k < len(x); k++ {
x[k] = nil
}
x = x[:j]
Alternative implementation:
Alternative implementation:
import "math/rand"
Alternative implementation:
Alternative implementation:
import "sync"
var mu sync.RWMutex
Alternative implementation:
fn main() {
let matrix = vec![
vec![1, 2, 3],
vec![4, 5, 6],
];
foo(&matrix);
}
Alternative implementation:
let a = [
[1, 2, 3],
[4, 5, 6],
];
foo(a);
If x is nil or there is no such element, delete is a no-op. x has type mut HashSet
Explains what happens if
e was already absent Alternative implementation: returns true if value was present.
from x.
delete(x, e)
Alternative implementation:
x has type map[E]bool use std::collections::HashSet;
m := make(map[Foo]string)
Mention the conditions
on Foo required to make Foo can be used as a key type if all of its fields are
it a possible map key comparable with ==
type.
283 Split with a custom
string separator import "strings" let parts = s.split(sep);
Build the list parts
parts := strings.Split(s, sep) split returns an iterator.
consisting of substrings
of input string s, s may have type &str or String.
parts has type []string.
separated by the string
sep. Alternative implementation:
Alternative implementation:
let s = a + b;
slices.SortFunc(items[i:j], c)
Alternative implementation:
Alternative implementation:
import "golang.org/x/exp/slices"
items = slices.Delete(items, i, j)
var s = new(Stack[string])
s.Push(x)
y := s.Pop()
lowerc := unicode.ToLow
er(c)
lowerd := unicode.ToLow
er(d)
s = s[sizec:]
t = t[sized:]
}
}
Alternative implementation:
import (
"sort"
"strings"
)
Alternative implementation:
import "golang.org/x/exp/slices"
Alternative implementation:
import "golang.org/x/exp/maps"
y := maps.Clone(x)
x = slices.Grow(x, 200)
m, n := len(in), len(in[0])
out = make(M, m)
for i := range out {
out[i] = buf[:n:n]
buf = buf[n:]
copy(out[i], in[i])
}
return out
}
Alternative implementation:
import "crypto/rand"
_, err := rand.Read(a)
Alternative implementation:
Alternative implementation:
Alternative implementation:
import "math/rand"
q := new(Queue[string])
q.Enqueue(x)
q.Enqueue(y)
z := q.Dequeue()
a := maps.Values(m)