Programming-Idioms.org


Alternative implementation...

Alternative implementation...

use std::collections::HashMap;
let x: HashMap<&str, i32> = [ ("one", 1), ("two", 2),
].iter().cloned().collect();

Alternative implementation...

y := make([]T, len(x)) perm := rand.Perm(len(x)) for i, v := range perm { y[v] = x[i] }
use rand::seq::SliceRandom; use rand::thread_rng;
let mut rng = thread_rng();
x.shuffle(&mut rng);

Alternative implementation...

rand.Shuffle(len(x), func(i, j int) { x[i], x[j] = x[j], x[i]
})

Alternative implementation...

func pickT(x []T) T { return x[rand.Intn(len(x))] }
use rand::seq::SliceRandom;
let mut rng = rand::thread_rng();
let choice = x.choose(&mut rng).unwrap();

Alternative implementation...

list.iter().any(|v| v == &x)

Alternative implementation...

(&list).into_iter().any(|v| v == &x)

Alternative implementation...

use rand::distributions::Uniform;
Uniform::new_inclusive(a, b).sample(&mut rand::thread_rng())

Alternative implementation...

20

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

func search(m [][]int, x int) (bool, int, int) { for i := range m { for j, v := range m[i] { if v == x { return true, i, j } } } return false, 0, 0 }
fn search<T: Eq>(m: &Vec<Vec<T>>, x: &T) -> Option<(usize, usize)> { for (i, row) in m.iter().enumerate() { for (j, column) in row.iter().enumerate() { if *column == *x { return Some((i, j)); } } } None
}

Alternative implementation...

i, err := strconv.ParseInt(s, 10, 0)
let i: i32 = s.parse().unwrap_or(0);

Alternative implementation...

let i = match s.parse::<i32>() { Ok(i) => i, Err(_e) => { -1 }
};

Alternative implementation...

func make2D(m, n int) [][]float64 { buf := make([]float64, m*n) x := make([][]float64, m) for i := range x { x[i] = buf[:n:n] buf = buf[n:] } return x
}
let mut x = [[0.0; N] ; M];

Alternative implementation...

func make3D(m, n, p int) [][][]float64 { buf := make([]float64, m*n*p) x := make([][][]float64, m) for i := range x { x[i] = make([][]float64, n) for j := range x[i] { x[i][j] = buf[:p:p] buf = buf[p:] } } return x }
28

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

type ItemPSorter []Item
func (s ItemPSorter) Len() int{ return len(s) }
func (s ItemPSorter) Less(i,j int) bool{ return s[i].p<s[j].p }
func (s ItemPSorter) Swap(i,j int) { s[i],s[j] = s[j],s[i] } func sortItems(items []Item){ sorter := ItemPSorter(items) sort.Sort(sorter)
}
items.sort_by(|a,b|a.p.cmp(&b.p));

Alternative implementation...

less := func(i, j int) bool { return items[i].p < items[j].p } sort.Slice(items, less)
items.sort_by_key(|item| item.p);

Alternative implementation...

copy(items[i:], items[i+1:]) items[len(items)-1] = nil items = items[:len(items)-1]

Alternative implementation...

extern crate rayon; use rayon::prelude::*;
(0..1000).into_par_iter().for_each(f);

Alternative implementation...

fn factorial(num: u64) -> u64 { match num { 0 | 1 => 1, _ => factorial(num - 1) * num, }
}

Alternative implementation...

x := make(map[T]struct{})

Alternative implementation...

fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C { move |x| g(f(x))
}

Alternative implementation...

fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C { move |x| g(f(x))
}
37

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

type PayFactory func(Company, *Employee, *Employee) Payroll type CustomPayFactory func(*Employee) Payroll func CurryPayFactory(pf PayFactory,company Company, boss *Employee) CustomPayFactory { return func(e *Employee) Payroll { return pf(company, boss, e) }
}
fn add(a: u32, b: u32) -> u32 { a + b
} let add5 = move |x| add(5, x); 

Alternative implementation...

use substring::Substring;
let t = s.substring(i, j);
41

Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i]
}
t := string(runes)
let t = s.chars().rev().collect::<String>();

Alternative implementation...

let t: String = s.chars().rev().collect();

Alternative implementation...

let s = r#"Huey
Dewey
Louie"#;

Alternative implementation...

chunks := strings.Fields(s)

Alternative implementation...

let s = x.iter().sum::<i32>();

Alternative implementation...

s := strconv.FormatInt(i, 10)

Alternative implementation...

s := fmt.Sprintf("%d", i)
57

Create list y containing items from list x satisfying predicate p. Respect original ordering. Don't modify x in-place.

y := make([]T, 0, len(x)) for _, v := range x{ if p(v){ y = append(y, v) } }
let y: Vec<_> = x.iter().filter(p).collect();

Alternative implementation...

let lines = fs::read_to_string(f).expect("Can't read file.");

Alternative implementation...

use std::time::SystemTime;
let d = SystemTime::now();

Alternative implementation...

Alternative implementation...

x := make([]uint64, (n+63)/64)

Alternative implementation...

r := rand.New(rand.NewSource(s))

Alternative implementation...

import "math/rand" import "time"
r := rand.New(rand.NewSource(time.Now().UnixNano()))

Alternative implementation...

use itertools::Itertools;
println!("{}", std::env::args().skip(1).format(" "));
74

Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.

extern crate num; use num::Integer; use num::bigint::BigInt;
75

Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.

gcd.GCD(nil, nil, a, b) x.Div(a, gcd).Mul(x, b)
extern crate num; use num::Integer; use num::bigint::BigInt;

Alternative implementation...

import "fmt" import "math/big"
s := fmt.Sprintf("%b", x)

Alternative implementation...

for done := false; !done; { someThing() someOtherThing() done = !c() }

Alternative implementation...

90

Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.

type Foo struct { x int
} func (f *Foo) X() int { return f.x
}
struct Foo { x: usize
} impl Foo { pub fn new(x: usize) -> Self { Foo { x } } pub fn x<'a>(&'a self) -> &'a usize { &self.x } pub fn bar(&mut self) { self.x += 1; }
}

Alternative implementation...

r, err := os.Open(filename)
if err != nil { return err
}
decoder := json.NewDecoder(r)
err = decoder.Decode(&x)
if err != nil { return err
}

Alternative implementation...

Alternative implementation...

let x = path.metadata()?.len();
100

Sort elements of array-like collection items, using a comparator c.

type ItemCSorter []Item func (s ItemCSorter) Len() int { return len(s) } func (s ItemCSorter) Less(i, j int) bool { return c(s[i], s[j]) } func (s ItemCSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func sortItems(items []Item) { sorter := ItemCSorter(items) sort.Sort(sorter) }
fn main() { let c = |a: &u32,b: &u32|a.cmp(b); let mut v = vec![1,7,5,2,3]; v.sort_by(c); println!("{:#?}",v); } 

Alternative implementation...

type ItemsSorter struct { items []Item c func(x, y Item) bool } func (s ItemsSorter) Len() int { return len(s.items) } func (s ItemsSorter) Less(i, j int) bool { return s.c(s.items[i], s.items[j]) } func (s ItemsSorter) Swap(i, j int) { s.items[i], s.items[j] = s.items[j], s.items[i] } func sortItems(items []Item, c func(x, y Item) bool) { sorter := ItemsSorter{ items, c, } sort.Sort(sorter) }

Alternative implementation...

sort.Slice(items, func(i, j int) bool { return c(items[i], items[j]) })

Alternative implementation...

[dependencies] ureq = "1.0"
let s = ureq::get(u).call().into_string()?;
102

Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.

import "fmt" import "io" import "net/http"
resp, err := http.Get(u)
if err != nil { return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 { return fmt.Errorf("Status: %v", resp.Status)
}
out, err := os.Create("result.txt")
if err != nil { return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil { return err
}
extern crate reqwest; use reqwest::Client; use std::fs::File;
let client = Client::new();
match client.get(&u).send() { Ok(res) => { let file = File::create("result.txt")?; ::std::io::copy(res, file)?; }, Err(e) => eprintln!("failed to send request: {}", e),
};

Alternative implementation...

let s = std::env::current_exe() .expect("Can't get the exec path") .file_name() .expect("Can't get the exec name") .to_string_lossy() .into_owned();

Alternative implementation...

import "fmt" import "sort"
type entry struct { key string value int
} entries := make([]entry, 0, len(mymap))
for k, x := range mymap { entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].value < entries[j].value
}) for _, e := range entries { fmt.Println("Key =", e.key, ", Value =", e.value)
}
let mut items: Vec<_> = mymap.iter().collect();
items.sort_by_key(|item| item.1);
for (k, x) in items { println!("[{},{}]", k, x);
}
118

Create set y from list x.
x may contain duplicates. y is unordered and has no repeated values.

y := make(map[T]struct{}, len(x))
for _, v := range x { y[v] = struct{}{}
}
use std::collections::HashSet;
let y: HashSet<_> = x.into_iter().collect();

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]
use itertools::Itertools;
let dedup: Vec<_> = x.iter().unique().collect();

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]

Alternative implementation...

_, err := fmt.Scanf("%d", &n)
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();

Alternative implementation...

let n: i32 = std::io::stdin() .lock() .lines() .next() .expect("stdin should be available") .expect("couldn't read from stdin") .trim() .parse() .expect("input was not an integer");
121

Listen UDP traffic on port p and read 1024 bytes into buffer b.

import ( "fmt" "net" "os" )
ServerAddr,err := net.ResolveUDPAddr("udp",p)
if err != nil { return err
}
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil { return err
}
defer ServerConn.Close()
n,addr,err := ServerConn.ReadFromUDP(b[:1024])
if err != nil { return err
}
if n<1024 { return fmt.Errorf("Only %d bytes could be read.", n)
}
let mut b = [0 as u8; 1024];
let sock = UdpSocket::bind(("localhost", p)).unwrap();
sock.recv_from(&mut b).unwrap();

Alternative implementation...

func binarySearch(a []int, x int) int { i := sort.SearchInts(a, x) if i < len(a) && a[i] == x { return i } return -1 }

Alternative implementation...

func binarySearch(a []T, x T) int { f := func(i int) bool { return a[i] >= x } i := sort.Search(len(a), f) if i < len(a) && a[i] == x { return i } return -1 }

Alternative implementation...

t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)
129

Call a function f on every vertex accessible from vertex start, in breadth-first prefix order

func (start *Vertex) Bfs(f func(*Vertex)) { queue := []*Vertex{start} seen := map[*Vertex]bool{start: true} for len(queue) > 0 { v := queue[0] queue = queue[1:] f(v) for next, isEdge := range v.Neighbours { if isEdge && !seen[next] { queue = append(queue, next) seen[next] = true } } } }
use std::rc::{Rc, Weak}; use std::cell::RefCell;
struct Vertex<V> { value: V, neighbours: Vec<Weak<RefCell<Vertex<V>>>>,
} // ... fn bft(start: Rc<RefCell<Vertex<V>>>, f: impl Fn(&V)) { let mut q = vec![start]; let mut i = 0; while i < q.len() { let v = Rc::clone(&q[i]); i += 1; (f)(&v.borrow().value); for n in &v.borrow().neighbours { let n = n.upgrade().expect("Invalid neighbour"); if q.iter().all(|v| v.as_ptr() != n.as_ptr()) { q.push(n); } } }
}
130

Call a function f on every vertex accessible for vertex v, in depth-first prefix order

func (v *Vertex) Dfs(f func(*Vertex), seen map[*Vertex]bool) { seen[v] = true f(v) for next, isEdge := range v.Neighbours { if isEdge && !seen[next] { next.Dfs(f, seen) } } }
use std::rc::{Rc, Weak}; use std::cell::RefCell;
struct Vertex<V> { value: V, neighbours: Vec<Weak<RefCell<Vertex<V>>>>,
} // ... fn dft_helper(start: Rc<RefCell<Vertex<V>>>, f: &impl Fn(&V), s: &mut Vec<*const Vertex<V>>) { s.push(start.as_ptr()); (f)(&start.borrow().value); for n in &start.borrow().neighbours { let n = n.upgrade().expect("Invalid neighbor"); if s.iter().all(|&p| p != n.as_ptr()) { Self::dft_helper(n, f, s); } }
}

Alternative implementation...

match true { _ if c1 => f1(), _ if c2 => f2(), _ if c3 => f3(), _ => (),
}

Alternative implementation...

extern crate regex; use regex::RegexBuilder;
let re = RegexBuilder::new(word) .case_insensitive(true) .build().unwrap(); ok = re.is_match(s);

Alternative implementation...

let ok = s.to_ascii_lowercase().contains(&word.to_ascii_lowercase());

Alternative implementation...

for i, y := range items { if y == x { copy(items[i:], items[i+1:]) items[len(items)-1] = nil items = items[:len(items)-1] break } }

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...

isNotDigit := func(c rune) bool { return c < '0' || c > '9' } b := strings.IndexFunc(s, isNotDigit) == -1
let b = s.chars().all(char::is_numeric);

Alternative implementation...

import "fmt" import "math/big"
s := fmt.Sprintf("%x", x)

Alternative implementation...

let f: f32 = s.parse().unwrap();

Alternative implementation...

import ( "fmt" "strings" "unicode" )
t := strings.Map(func(r rune) rune { if r > unicode.MaxASCII { return -1 } return r
}, s)
let t = s.chars().filter(|c| c.is_ascii()).collect::<String>();

Alternative implementation...

import "fmt" import "path/filepath" import "strings"
sep := fmt.Sprintf("%c", filepath.Separator) p = strings.TrimSuffix(p, sep)
let p = p.strip_suffix(std::path::is_separator);

Alternative implementation...

import "fmt" import "strconv"
var buf [7]byte buf[0] = '#' for i := 0; i < 3; i++ { sub1 := c1[1+2*i : 3+2*i] sub2 := c2[1+2*i : 3+2*i] v1, _ := strconv.ParseInt(sub1, 16, 0) v2, _ := strconv.ParseInt(sub2, 16, 0) v := (v1 + v2) / 2 sub := fmt.Sprintf("%02X", v) copy(buf[1+2*i:3+2*i], sub) } c := string(buf[:])
158
Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements.

Each element must have same probability to be picked.

Each element from x must be picked at most once.


Explain if the original ordering is preserved or not.
y := make([]T, k)
perm := rand.Perm(len(x))
for i, v := range perm[:k] { y[i] = x[v]
}
let mut rng = &mut rand::thread_rng();
let y = x.choose_multiple(&mut rng, k).cloned().collect::<Vec<_>>();
159

Define a Trie data structure, where entries have an associated value.
(Not all nodes are entries)

type Trie struct { c rune children map[rune]*Trie isEntry bool value V }
struct Trie { val: String, nodes: Vec<Trie>
}

Alternative implementation...

if let Some(arg) = ::std::env::args().nth(1) { match arg.as_str() { "f" => fox(), "b" => box(), _ => eprintln!("invalid argument: {}", arg), };
} else { eprintln!("missing argument");
}

Alternative implementation...

func openbrowser(url string) { var err error switch runtime.GOOS { case "linux": err = exec.Command("xdg-open", url).Start() case "windows": err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() case "darwin": err = exec.Command("open", url).Start() default: err = fmt.Errorf("unsupported platform") } if err != nil { log.Fatal(err) } }

Alternative implementation...

let x = items.last().unwrap();

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...

let t = if s.starts_with(p) { &s[p.len()..] } else { s };

Alternative implementation...

let t = s.strip_prefix(p).unwrap_or_else(|| s);

Alternative implementation...

let t = s.strip_suffix(w).unwrap_or(s);

Alternative implementation...

import "github.com/floscodes/golang-thousands" import "strconv"
n := strconv.Itoa(23489)
s := thousands.Separate(n, "en")

Alternative implementation...

import "net/http" import "net/url"
response, err := http.PostForm(u, formValues)

Alternative implementation...

let mut s = String::with_capacity(2 * n);
for byte in a { write!(s, "{:02X}", byte)?;
}

Alternative implementation...

let x = std::fs::read_dir(d)?.collect::<Result<Vec<_>, _>()?;
182

Output the source of the program.

package main import "fmt" func main() { fmt.Printf("%s%c%s%c\n", s, 0x60, s, 0x60)
} var s = `package main import "fmt" func main() { fmt.Printf("%s%c%s%c\n", s, 0x60, s, 0x60)
} var s = `
fn main() { let x = "fn main() {\n let x = "; let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; print!("{}{:?}; let y = {:?}; {}", x, x, y, y)
}

Alternative implementation...

fn main(){print!("{},{0:?})}}","fn main(){print!(\"{},{0:?})}}\"")}
184

Assign to variable t a string representing the day, month and year of the day after the current date.

t := time.Now().Add(24 * time.Hour).Format("2006-01-02")
let t = chrono::Utc::now().date().succ().to_string();

Alternative implementation...

go func() { time.Sleep(30 * time.Second) f(42)
}()

Alternative implementation...

Alternative implementation...

foo := os.Getenv("FOO")
if foo == "" { foo = "none"
}
let foo = env::var("FOO").unwrap_or("none".to_string());

Alternative implementation...

let foo = match env::var("FOO") { Ok(val) => val, Err(_e) => "none".to_string(),
};

Alternative implementation...

err := os.MkdirAll(path, os.ModeDir)
215

Prepend extra character c at the beginning of string s to make sure its length is at least m.
The length is the number of characters, not the number of bytes.

import "strings" import "utf8"
if n := utf8.RuneCountInString(s); n < m { s = strings.Repeat(c, m-n) + s
}
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
if let Some(columns_short) = m.checked_sub(s.width()) { let padding_width = c .width() .filter(|n| *n > 0) .expect("padding character should be visible"); // Saturate the columns_short let padding_needed = columns_short + padding_width - 1 / padding_width; let mut t = String::with_capacity(s.len() + padding_needed); t.extend((0..padding_needed).map(|_| c) t.push_str(&s); s = t;
}
217

Create a zip-file with filename name and add the files listed in list to that zip-file.

import "archive/zip" import "bytes" import "os" import "io" import "io/ioutil"
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
for _, filename := range list { input, err := os.Open(filename) if err != nil { return err } output, err := w.Create(filename) if err != nil { return err } _, err = io.Copy(output, input) if err != nil { return err }
} err := w.Close()
if err != nil { return err
} err = ioutil.WriteFile(name, buf.Bytes(), 0777)
if err != nil { return err
}
use zip::write::FileOptions;
let path = std::path::Path::new(_name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file); zip.start_file("readme.txt", FileOptions::default())?; zip.write_all(b"Hello, World!\n")?;
zip.finish()?;

Alternative implementation...

use zip::write::FileOptions;
fn zip(_name: &str, _list: Vec<&str>) -> zip::result::ZipResult<()>
{ let path = std::path::Path::new(_name); let file = std::fs::File::create(&path).unwrap(); let mut zip = zip::ZipWriter::new(file); for i in _list.iter() { zip.start_file(i as &str, FileOptions::default())?; } zip.finish()?; Ok(())
}
218

Create list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.

seta := make(map[T]bool, len(a))
for _, x := range a { seta[x] = true
}
setb := make(map[T]bool, len(a))
for _, y := range b { setb[y] = true
} var c []T
for x := range seta { if setb[x] { c = append(c, x) }
}
use std::collections::HashSet;
let unique_a = a.iter().collect::<HashSet<_>>();
let unique_b = b.iter().collect::<HashSet<_>>(); let c = unique_a.intersection(&unique_b).collect<Vec<_>>();

Alternative implementation...

use std::collections::HashSet;
let set_a: HashSet<_> = a.into_iter().collect();
let set_b: HashSet<_> = b.into_iter().collect();
let c = set_a.intersection(&set_b);

Alternative implementation...

let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
223
Loop through list items checking a condition. Do something else if no matches are found.A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.

items := []string{"foo", "bar", "baz", "qux"} for _, item := range items { if item == "baz" { fmt.Println("found it") goto forelse }
}
{ fmt.Println("never found it")
}
forelse:
let mut found = false;
for item in items { if item == &"baz" { println!("found it"); found = true; break; }
}
if !found { println!("never found it");
}

Alternative implementation...

if let None = items.iter().find(|&&item| item == "rockstar programmer") { println!("NotFound"); };

Alternative implementation...

items .iter() .find(|&&item| item == "rockstar programmer") .or_else(|| { println!("NotFound"); Some(&"rockstar programmer") });

Alternative implementation...

items = append(items, x)
copy(items[1:], items)
items[0] = x
227
Create new list y containing the same elements as list x.

Subsequent modifications of y must not affect x (except for the contents referenced by the elements themselves if they contain pointers).

y := make([]T, len(x))
copy(y, x)
228

Copy the file at path src to dst.

import "io/ioutil" import "os"
func copy(dst, src string) error { data, err := ioutil.ReadFile(src) if err != nil { return err } stat, err := os.Stat(src) if err != nil { return err } return ioutil.WriteFile(dst, data, stat.Mode())
}

Alternative implementation...

import "io/ioutil" import "os"
func copy(dst, src string) error { data, err := ioutil.ReadFile(src) if err != nil { return err } stat, err := os.Stat(src) if err != nil { return err } err = ioutil.WriteFile(dst, data, stat.Mode()) if err != nil { return err } return os.Chmod(dst, stat.Mode())
}

Alternative implementation...

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.Mode()) if err != nil { return err } defer g.Close() _, err = io.Copy(g, f) if err != nil { return err } return os.Chmod(dst, stat.Mode())
}
230

Cancel an ongoing processing p if it has not finished after 5s.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p(ctx)

Alternative implementation...

q := new(big.Rat)
q.SetFrac(a, b)

Alternative implementation...

Alternative implementation...

c := new(big.Int)
c.Xor(a, b)

Alternative implementation...

var c T
for i := range a { c[i] = a[i] ^ b[i]
}
240

Lists a and b have the same length. Apply the same permutation to a and b to have them sorted based on the values of a.

type sorter struct { k []K t []T
} func (s *sorter) Len() int { return len(s.k)
} func (s *sorter) Swap(i, j int) { s.k[i], s.k[j] = s.k[j], s.k[i] s.t[i], s.t[j] = s.t[j], s.t[i]
} func (s *sorter) Less(i, j int) bool { return s.k[i] < s.k[j]
} sort.Sort(&sorter{ k: a, t: b,
})
let mut tmp: Vec<_> = a.iter().zip(b).collect();
tmp.as_mut_slice().sort_by_key(|(&x, _y)| x);
let (aa, bb): (Vec<i32>, Vec<i32>) = tmp.into_iter().unzip();