国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust vs Go:常用語法對比(六)

這篇具有很好參考價值的文章主要介紹了Rust vs Go:常用語法對比(六)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Rust vs Go:常用語法對比(六),后端

題圖來自[1]


101. Load from HTTP GET request into a string

Make an HTTP request with method GET to URL u, then store the body of the response in string s.

發(fā)起http請求

package?main

import?(
?"fmt"
?"io/ioutil"
?"net"
?"net/http"
)

func?main()?{
?u?:=?"http://"?+?localhost?+?"/hello?name=Inigo+Montoya"

?res,?err?:=?http.Get(u)
?check(err)
?buffer,?err?:=?ioutil.ReadAll(res.Body)
?res.Body.Close()
?check(err)
?s?:=?string(buffer)

?fmt.Println("GET??response:",?res.StatusCode,?s)
}

const?localhost?=?"127.0.0.1:3000"

func?init()?{
?http.HandleFunc("/hello",?myHandler)
?startServer()
}

func?myHandler(w?http.ResponseWriter,?r?*http.Request)?{
?fmt.Fprintf(w,?"Hello?%s",?r.FormValue("name"))
}

func?startServer()?{
?listener,?err?:=?net.Listen("tcp",?localhost)
?check(err)

?go?http.Serve(listener,?nil)
}

func?check(err?error)?{
?if?err?!=?nil?{
??panic(err)
?}
}

res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step.

GET response: 200 Hello Inigo Montoya


extern?crate?reqwest;
use?reqwest::Client;
let?client?=?Client::new();
let?s?=?client.get(u).send().and_then(|res|?res.text())?;

or

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

or

[dependencies]
error-chain?=?"0.12.4"
reqwest?=?{?version?=?"0.11.2",?features?=?["blocking"]?}

use?error_chain::error_chain;
use?std::io::Read;
let?mut?response?=?reqwest::blocking::get(u)?;
let?mut?s?=?String::new();
response.read_to_string(&mut?s)?;

102. Load from HTTP GET request into a file

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.

發(fā)起http請求

package?main

import?(
?"fmt"
?"io"
?"io/ioutil"
?"net"
?"net/http"
?"os"
)

func?main()?{
?err?:=?saveGetResponse()
?check(err)
?err?=?readFile()
?check(err)

?fmt.Println("Done.")
}

func?saveGetResponse()?error?{
?u?:=?"http://"?+?localhost?+?"/hello?name=Inigo+Montoya"

?fmt.Println("Making?GET?request")
?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)
?}

?fmt.Println("Saving?data?to?file")
?out,?err?:=?os.Create("/tmp/result.txt")
?if?err?!=?nil?{
??return?err
?}
?defer?out.Close()
?_,?err?=?io.Copy(out,?resp.Body)
?if?err?!=?nil?{
??return?err
?}
?return?nil
}

func?readFile()?error?{
?fmt.Println("Reading?file")
?buffer,?err?:=?ioutil.ReadFile("/tmp/result.txt")
?if?err?!=?nil?{
??return?err
?}
?fmt.Printf("Saved?data?is?%q\n",?string(buffer))
?return?nil
}

const?localhost?=?"127.0.0.1:3000"

func?init()?{
?http.HandleFunc("/hello",?myHandler)
?startServer()
}

func?myHandler(w?http.ResponseWriter,?r?*http.Request)?{
?fmt.Fprintf(w,?"Hello?%s",?r.FormValue("name"))
}

func?startServer()?{
?listener,?err?:=?net.Listen("tcp",?localhost)
?check(err)

?go?http.Serve(listener,?nil)
}

func?check(err?error)?{
?if?err?!=?nil?{
??panic(err)
?}
}

resp has type *http.Response. It is idiomatic and strongly recommended to check errors at each step, except for the calls to Close.

Making?GET?request
Saving?data?to?file
Reading?file
Saved?data?is?"Hello?Inigo?Montoya"
Done.

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),
};

105. Current executable name

Assign to string s the name of the currently executing program (but not its full path).

當前可執(zhí)行文件名稱

將當前正在執(zhí)行的程序的名稱分配給字符串s(但不是它的完整路徑)。

package?main

import?(
?"fmt"
?"os"
?"path/filepath"
)

func?main()?{
?var?s?string

?path?:=?os.Args[0]
?s?=?filepath.Base(path)

?fmt.Println(s)
}

play


fn?get_exec_name()?->?Option<String>?{
????std::env::current_exe()
????????.ok()
????????.and_then(|pb|?pb.file_name().map(|s|?s.to_os_string()))
????????.and_then(|s|?s.into_string().ok())
}

fn?main()?->?()?{
????let?s?=?get_exec_name().unwrap();
????println!("{}",?s);
}

playground

or

fn?main()?{
????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();
????
????println!("{}",?s);
}

playground


106. Get program working directory

Assign to string dir the path of the working directory. (This is not necessarily the folder containing the executable itself)

獲取程序的工作路徑

package?main

import?(
?"fmt"
?"os"
)

func?main()?{
?dir,?err?:=?os.Getwd()
?fmt.Println(dir,?err)
}

/ <nil>


use?std::env;

fn?main()?{
????let?dir?=?env::current_dir().unwrap();

????println!("{:?}",?dir);
}

"/playground"


107. Get folder containing current program

Assign to string dir the path of the folder containing the currently running executable. (This is not necessarily the working directory, though.)

獲取包含當前程序的文件夾

package?main

import?(
?"fmt"
?"os"
?"path/filepath"
)

func?main()?{
?var?dir?string

?programPath?:=?os.Args[0]
?absolutePath,?err?:=?filepath.Abs(programPath)
?if?err?!=?nil?{
??panic(err)
?}
?dir?=?filepath.Dir(absolutePath)

?fmt.Println(dir)
}

/tmpfs


let?dir?=?std::env::current_exe()?
????.canonicalize()
????.expect("the?current?exe?should?exist")
????.parent()
????.expect("the?current?exe?should?be?a?file")
????.to_string_lossy()
????.to_owned();

Rust doesn't represent paths as Strings, so we need to convert the Path returned from Path::parent. This code chooses to do this lossily, replacing characters it doesn't recognize with ?


109. Number of bytes of a type

Set n to the number of bytes of a variable t (of type T).

獲取某個類型的字節(jié)數(shù)

package?main

import?(
?"fmt"
?"reflect"
)

func?main()?{
?var?t?T
?tType?:=?reflect.TypeOf(t)
?n?:=?tType.Size()

?fmt.Println("A",?tType,?"object?is",?n,?"bytes.")
}

type?Person?struct?{
?FirstName?string
?Age???????int
}

//?T?is?a?type?alias,?to?stick?to?the?idiom?statement.
//?T?has?the?same?memory?footprint?per?value?as?Person.
type?T?Person

A main.T object is 24 bytes.


//?T?has?(8?+?4)?==?12?bytes?of?data
struct?T(f64,?i32);

fn?main()?{
????let?n?=?::std::mem::size_of::<T>();

????println!("{}?bytes",?n);
????//?T?has?size?16,?which?is?"the?offset?in?bytes?between?successive?elements?in?an?array?with?item?type?T"
}

16 bytes


110. Check if string is blank

Set boolean blank to true if string s is empty, or null, or contains only whitespace ; false otherwise.

檢查字符串是否空白

package?main

import?(
?"fmt"
?"strings"
)

func?main()?{
?for?_,?s?:=?range?[]string{
??"",
??"a",
??"?",
??"\t?\n",
??"_",
?}?{
??blank?:=?strings.TrimSpace(s)?==?""

??if?blank?{
???fmt.Printf("%q?is?blank\n",?s)
??}?else?{
???fmt.Printf("%q?is?not?blank\n",?s)
??}
?}
}
""?is?blank
"a"?is?not?blank
"?"?is?blank
"\t?\n"?is?blank
"_"?is?not?blank

fn?main()?{
????let?list?=?vec!["",?"?",?"??",?"\t",?"\n",?"a",?"?b?"];
????for?s?in?list?{
????????let?blank?=?s.trim().is_empty();

????????if?blank?{
????????????println!("{:?}\tis?blank",?s)
????????}?else?{
????????????println!("{:?}\tis?not?blank",?s)
????????}
????}
}
""?is?blank
"?"?is?blank
"??"?is?blank
"\t"?is?blank
"\n"?is?blank
"a"?is?not?blank
"?b?"?is?not?blank

111. Launch other program

From current process, run program x with command-line parameters "a", "b".

運行其他程序

package?main

import?(
?"fmt"
?"os/exec"
)

func?main()?{
?err?:=?exec.Command("x",?"a",?"b").Run()
?fmt.Println(err)
}

exec: "x": executable file not found in $PATH


use?std::process::Command;

fn?main()?{
????let?child?=?Command::new("ls")
????????.args(&["/etc"])
????????.spawn()
????????.expect("failed?to?execute?process");

????let?output?=?child.wait_with_output().expect("Failed?to?wait?on?child");
????let?output?=?String::from_utf8(output.stdout).unwrap();

????println!("{}",?output);
}

X11
adduser.conf
alternatives
apt
bash.bashrc
bash_completion.d
bindresvport.blacklist
ca-certificates
ca-certificates.conf
cron.d
cron.daily
debconf.conf
debian_version
default
deluser.conf
dpkg
e2scrub.conf
emacs
environment
ethertypes
fstab
gai.conf
group
group-
gshadow
gshadow-
gss
host.conf
hostname
hosts
init.d
inputrc
issue
issue.net
kernel
ld.so.cache
ld.so.conf
ld.so.conf.d
ldap
legal
libaudit.conf
localtime
logcheck
login.defs
logrotate.d
lsb-release
machine-id
magic
magic.mime
mailcap
mailcap.order
mime.types
mke2fs.conf
mtab
networks
nsswitch.conf
opt
os-release
pam.conf
pam.d
passwd
passwd-
perl
profile
profile.d
protocols
python2.7
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rcS.d
resolv.conf
rmt
rpc
security
selinux
services
shadow
shadow-
shells
skel
ssh
ssl
subgid
subgid-
subuid
subuid-
sysctl.conf
sysctl.d
systemd
terminfo
timezone
update-motd.d
xattr.conf
xdg

or

use?std::process::Command;

fn?main()?{
????let?output?=?Command::new("ls")
????????.args(&["/etc"])
????????.output()
????????.expect("failed?to?execute?process");

????let?output?=?String::from_utf8(output.stdout).unwrap();

????println!("{}",?output);
}

or

use?std::process::Command;

fn?main()?{
????let?status?=?Command::new("ls")
????????.args(&["/etc"])
????????.status()
????????.expect("failed?to?execute?process");

????//?exit?code?is?outputted?after?_ls_?runs
????println!("{}",?status);
}


112. Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

遍歷map,按key排序

package?main

import?(
?"fmt"
?"sort"
)

func?main()?{
?mymap?:=?map[string]int{
??"one":???1,
??"two":???2,
??"three":?3,
??"four":??4,
?}

?keys?:=?make([]string,?0,?len(mymap))
?for?k?:=?range?mymap?{
??keys?=?append(keys,?k)
?}
?sort.Strings(keys)

?for?_,?k?:=?range?keys?{
??x?:=?mymap[k]
??fmt.Println("Key?=",?k,?",?Value?=",?x)
?}
}

Key?=?four?,?Value?=?4
Key?=?one?,?Value?=?1
Key?=?three?,?Value?=?3
Key?=?two?,?Value?=?2

use?std::collections::BTreeMap;

fn?main()?{
????let?mut?mymap?=?BTreeMap::new();
????mymap.insert("one",?1);
????mymap.insert("two",?2);
????mymap.insert("three",?3);
????mymap.insert("four",?4);
????mymap.insert("five",?5);
????mymap.insert("six",?6);

????//?Iterate?over?map?entries,?ordered?by?keys,?which?is?NOT?the?numerical?order
????for?(k,?x)?in?mymap?{
????????println!("({},?{})",?k,?x);
????}
}

(five,?5)
(four,?4)
(one,?1)
(six,?6)
(three,?3)
(two,?2)

113. Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x. Note that multiple entries may exist for the same value x.

遍歷map,按值排序

package?main

import?(
?"fmt"
?"sort"
)

type?entry?struct?{
?key???string
?value?int
}
type?entries?[]entry

func?(list?entries)?Len()?int???????????{?return?len(list)?}
func?(list?entries)?Less(i,?j?int)?bool?{?return?list[i].value?<?list[j].value?}
func?(list?entries)?Swap(i,?j?int)??????{?list[i],?list[j]?=?list[j],?list[i]?}

func?main()?{
?mymap?:=?map[string]int{
??"one":???1,
??"two":???2,
??"three":?3,
??"four":??4,
??"dos":???2,
??"deux":??2,
?}

?entries?:=?make(entries,?0,?len(mymap))
?for?k,?x?:=?range?mymap?{
??entries?=?append(entries,?entry{key:?k,?value:?x})
?}
?sort.Sort(entries)

?for?_,?e?:=?range?entries?{
??fmt.Println("Key?=",?e.key,?",?Value?=",?e.value)
?}
}

Key?=?one?,?Value?=?1
Key?=?dos?,?Value?=?2
Key?=?deux?,?Value?=?2
Key?=?two?,?Value?=?2
Key?=?three?,?Value?=?3
Key?=?four?,?Value?=?4

or

package?main

import?(
?"fmt"
?"sort"
)

func?main()?{
?mymap?:=?map[string]int{
??"one":???1,
??"two":???2,
??"three":?3,
??"four":??4,
??"dos":???2,
??"deux":??2,
?}

?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)
?}
}

Key?=?one?,?Value?=?1
Key?=?two?,?Value?=?2
Key?=?dos?,?Value?=?2
Key?=?deux?,?Value?=?2
Key?=?three?,?Value?=?3
Key?=?four?,?Value?=?4

use?itertools::Itertools;
use?std::collections::HashMap;

fn?main()?{
????let?mut?mymap?=?HashMap::new();
????mymap.insert(1,?3);
????mymap.insert(2,?6);
????mymap.insert(3,?4);
????mymap.insert(4,?1);
????
????for?(k,?x)?in?mymap.iter().sorted_by_key(|x|?x.1)?{
????????println!("[{},{}]",?k,?x);
????}
}
[4,1]
[1,3]
[3,4]
[2,6]

or

use?std::collections::HashMap;

fn?main()?{
????let?mut?mymap?=?HashMap::new();
????mymap.insert(1,?3);
????mymap.insert(2,?6);
????mymap.insert(3,?4);
????mymap.insert(4,?1);
????
????let?mut?items:?Vec<_>?=?mymap.iter().collect();
????items.sort_by_key(|item|?item.1);
????for?(k,?x)?in?items?{
????????println!("[{},{}]",?k,?x);
????}
}
[4,1]
[1,3]
[3,4]
[2,6]

114. Test deep equality

Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y. Tell if the code correctly handles recursive types.

深度判等

package?main

import?(
?"fmt"
?"reflect"
)

func?main()?{
?x?:=?Foo{9,?"Hello",?[]bool{false,?true},?map[int]float64{1:?1.0,?2:?2.0},?&Bar{"Babar"}}

?list?:=?[]Foo{
??{9,?"Bye",?[]bool{false,?true},?map[int]float64{1:?1.0,?2:?2.0},?&Bar{"Babar"}},
??{9,?"Hello",?[]bool{false,?false},?map[int]float64{1:?1.0,?2:?2.0},?&Bar{"Babar"}},
??{9,?"Hello",?[]bool{false,?true},?map[int]float64{1:?3.0,?2:?2.0},?&Bar{"Babar"}},
??{9,?"Hello",?[]bool{false,?true},?map[int]float64{1:?1.0,?5:?2.0},?&Bar{"Babar"}},
??{9,?"Hello",?[]bool{false,?true},?map[int]float64{1:?1.0,?2:?2.0},?&Bar{"Batman"}},
??{9,?"Hello",?[]bool{false,?true},?map[int]float64{1:?1.0,?2:?2.0},?&Bar{"Babar"}},
?}

?for?i,?y?:=?range?list?{
??b?:=?reflect.DeepEqual(x,?y)
??if?b?{
???fmt.Println("x?deep?equals?list[",?i,?"]")

??}?else?{
???fmt.Println("x?doesn't?deep?equal?list[",?i,?"]")
??}
?}
}

type?Foo?struct?{
?int
?str?????string
?bools???[]bool
?mapping?map[int]float64
?bar?????*Bar
}

type?Bar?struct?{
?name?string
}

x?doesn't?deep?equal?list[?0?]
x?doesn'
t?deep?equal?list[?1?]
x?doesn't?deep?equal?list[?2?]
x?doesn'
t?deep?equal?list[?3?]
x?doesn't?deep?equal?list[?4?]
x?deep?equals?list[?5?]

let?b?=?x?==?y;

The == operator can only be used by having a type implement PartialEq.


115. Compare dates

Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.

日期比較

package?main

import?(
?"fmt"
?"time"
)

func?main()?{
?d1?:=?time.Now()
?d2?:=?time.Date(2020,?time.November,?10,?23,?0,?0,?0,?time.UTC)

?b?:=?d1.Before(d2)

?fmt.Println(b)
}

true


extern?crate?chrono;
use?chrono::prelude::*;
let?b?=?d1?<?d2;

doc -- Struct chrono::Date[2]


116. Remove occurrences of word from string

Remove all occurrences of string w from string s1, and store the result in s2.

去除指定字符串

package?main

import?"fmt"
import?"strings"

func?main()?{
?var?s1?=?"foobar"
?var?w?=?"foo"
?s2?:=?strings.Replace(s1,?w,?"",?-1)
?fmt.Println(s2)
}

bar


fn?main()?{
????let?s1?=?"foobar";
????let?w?=?"foo";
????let?s2?=?s1.replace(w,?"");
????println!("{}",?s2);
}

bar

or

fn?main()?{
????let?s1?=?"foobar";
????let?w?=?"foo";

????let?s2?=?str::replace(s1,?w,?"");

????println!("{}",?s2);
}

bar


117. Get list size

獲取list的大小

package?main

import?"fmt"

func?main()?{
?//?x?is?a?slice
?x?:=?[]string{"a",?"b",?"c"}
?n?:=?len(x)
?fmt.Println(n)

?//?y?is?an?array
?y?:=?[4]string{"a",?"b",?"c"}
?n?=?len(y)
?fmt.Println(n)
}
3
4

fn?main()?{
????let?x?=?vec![11,?22,?33];

????let?n?=?x.len();

????println!("x?has?{}?elements",?n);
}

x has 3 elements


118. List to set

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

從list到set

package?main

import?"fmt"

func?main()?{
?x?:=?[]string{"b",?"a",?"b",?"c"}
?fmt.Println("x?=",?x)

?y?:=?make(map[string]struct{},?len(x))
?for?_,?v?:=?range?x?{
??y[v]?=?struct{}{}
?}

?fmt.Println("y?=",?y)
}
x?=?[b?a?b?c]
y?=?map[a:{}?b:{}?c:{}]

use?std::collections::HashSet;

fn?main()?{
????let?x:?Vec<i32>?=?vec![1,?7,?3,?1];
????println!("x:?{:?}",?x);

????let?y:?HashSet<_>?=?x.into_iter().collect();
????println!("y:?{:?}",?y);
}
x:?[1,?7,?3,?1]
y:?{1,?7,?3}

119. Deduplicate list

Remove duplicates from list x. Explain if original order is preserved.

list去重

package?main

import?"fmt"

func?main()?{
?type?T?string
?x?:=?[]T{"b",?"a",?"b",?"c"}
?fmt.Println("x?=",?x)

?y?:=?make(map[T]struct{},?len(x))
?for?_,?v?:=?range?x?{
??y[v]?=?struct{}{}
?}
?x2?:=?make([]T,?0,?len(y))
?for?_,?v?:=?range?x?{
??if?_,?ok?:=?y[v];?ok?{
???x2?=?append(x2,?v)
???delete(y,?v)
??}
?}
?x?=?x2

?fmt.Println("x?=",?x)
}

x?=?[b?a?b?c]
x?=?[b?a?c]

or

package?main

import?"fmt"

func?main()?{
?type?T?string
?x?:=?[]T{"b",?"a",?"b",?"b",?"c",?"b",?"a"}
?fmt.Println("x?=",?x)

?seen?:=?make(map[T]bool)
?j?:=?0
?for?_,?v?:=?range?x?{
??if?!seen[v]?{
???x[j]?=?v
???j++
???seen[v]?=?true
??}
?}
?x?=?x[:j]

?fmt.Println("x?=",?x)
}
x?=?[b?a?b?b?c?b?a]
x?=?[b?a?c]

or

package?main

import?"fmt"

type?T?*int64

func?main()?{
?var?a,?b,?c,?d?int64?=?11,?22,?33,?11
?x?:=?[]T{&b,?&a,?&b,?&b,?&c,?&b,?&a,?&d}
?print(x)

?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++?{
??//?Avoid?memory?leak
??x[i]?=?nil
?}
?x?=?x[:j]

?//?Now?x?has?only?distinct?pointers?(even?if?some?point?to?int64?values?that?are?the?same)
?print(x)
}

func?print(a?[]T)?{
?glue?:=?""
?for?_,?p?:=?range?a?{
??fmt.Printf("%s%d",?glue,?*p)
??glue?=?",?"
?}
?fmt.Println()
}
22,?11,?22,?22,?33,?22,?11,?11
22,?11,?33,?11

fn?main()?{
????let?mut?x?=?vec![1,?2,?3,?4,?3,?2,?2,?2,?2,?2,?2];
????x.sort();
????x.dedup();

????println!("{:?}",?x);
}

[1, 2, 3, 4]

or

use?itertools::Itertools;

fn?main()?{
????let?x?=?vec![1,?2,?3,?4,?3,?2,?2,?2,?2,?2,?2];
????let?dedup:?Vec<_>?=?x.iter().unique().collect();

????println!("{:?}",?dedup);
}

[1, 2, 3, 4]


120. Read integer from stdin

Read an integer value from the standard input into variable n

從標準輸入中讀取整數(shù)

package?main

import?(
?"fmt"
?"io/ioutil"
?"os"
)

//?This?string?simulates?the?keyboard?entry.
var?userInput?string?=?`42?017`

func?main()?{
?var?i?int
?_,?err?:=?fmt.Scan(&i)
?fmt.Println(i,?err)

?//?The?second?value?starts?with?0,?thus?is?interpreted?as?octal!
?var?j?int
?_,?err?=?fmt.Scan(&j)
?fmt.Println(j,?err)
}

//?The?Go?Playground?doesn't?actually?read?os.Stdin,?so?this
//?workaround?writes?some?data?on?virtual?FS?in?a?file,?and?then
//?sets?this?file?as?the?new?Stdin.
//
//?Note?that?the?init?func?is?run?before?main.
func?init()?{
?err?:=?ioutil.WriteFile("/tmp/stdin",?[]byte(userInput),?0644)
?if?err?!=?nil?{
??panic(err)
?}
?fileIn,?err?:=?os.Open("/tmp/stdin")
?if?err?!=?nil?{
??panic(err)
?}
?os.Stdin?=?fileIn
}

42?<nil>
15?<nil>

or

package?main

import?(
?"fmt"
?"io/ioutil"
?"os"
)

//?This?string?simulates?the?keyboard?entry.
var?userInput?string?=?`42?017`

func?main()?{
?var?i?int
?_,?err?:=?fmt.Scanf("%d",?&i)
?fmt.Println(i,?err)

?var?j?int
?_,?err?=?fmt.Scanf("%d",?&j)
?fmt.Println(j,?err)
}

//?The?Go?Playground?doesn't?actually?read?os.Stdin,?so?this
//?workaround?writes?some?data?on?virtual?FS?in?a?file,?and?then
//?sets?this?file?as?the?new?Stdin.
//
//?Note?that?the?init?func?is?run?before?main.
func?init()?{
?err?:=?ioutil.WriteFile("/tmp/stdin",?[]byte(userInput),?0644)
?if?err?!=?nil?{
??panic(err)
?}
?fileIn,?err?:=?os.Open("/tmp/stdin")
?if?err?!=?nil?{
??panic(err)
?}
?os.Stdin?=?fileIn
}
42?<nil>
17?<nil>

fn?get_input()?->?String?{
????let?mut?buffer?=?String::new();
????std::io::stdin().read_line(&mut?buffer).expect("Failed");
????buffer
}

let?n?=?get_input().trim().parse::<i64>().unwrap();

or

use?std::io;
let?mut?input?=?String::new();
io::stdin().read_line(&mut?input).unwrap();
let?n:?i32?=?input.trim().parse().unwrap();s

or

use?std::io::BufRead;
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");

參考資料

[1]

題圖來自: https://picx.zhimg.com/v2-363b653b2429b2f8073bc067b6c55f2d_720w.jpg?source=172ae18b

[2]

doc -- Struct chrono::Date: https://docs.rs/chrono/0.4.3/chrono/struct.Date.html

本文由 mdnice 多平臺發(fā)布文章來源地址http://www.zghlxwxcb.cn/news/detail-605822.html

到了這里,關于Rust vs Go:常用語法對比(六)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Rust vs Go:常用語法對比(十)

    Rust vs Go:常用語法對比(十)

    題圖來自 Rust vs. Golang: Which One is Better? [1] 182. Quine program Output the source of the program. 輸出程序的源代碼 輸出: 另一種寫法: //go:embed 入門 [2] Quine 是一種可以輸出自身源碼的程序。利用 go:embed 我們可以輕松實現(xiàn) quine 程序: 輸出: or 輸出: fn main(){print!(\\\"{},{0:?})}}\\\",\\\"fn main(){pri

    2024年02月15日
    瀏覽(23)
  • Rust vs Go:常用語法對比(十一)

    Rust vs Go:常用語法對比(十一)

    題目來自 Rust Vs Go: Which Language Is Better For Developing High-Performance Applications? [1] 202. Sum of squares Calculate the sum of squares s of data, an array of floating point values. 計算平方和 +1.094200e+000 32.25 205. Get an environment variable Read an environment variable with the name \\\"FOO\\\" and assign it to the string variable foo. If i

    2024年02月15日
    瀏覽(19)
  • Rust vs Go:常用語法對比(十二)

    Rust vs Go:常用語法對比(十二)

    題圖來自 Rust vs Go in 2023 [1] 221. Remove all non-digits characters Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 刪除所有非數(shù)字字符 168 [src/main.rs:7] t = \\\"14\\\" 222. Find first index of an element in list Set i to the first index in list items at which the element x can be found, or -1 if items doe

    2024年02月15日
    瀏覽(16)
  • Rust vs Go:常用語法對比(二)

    21. Swap values 交換變量a和b的值 輸出 a: 10, b: 3 or 輸出 22. Convert string to integer 將字符串轉換為整型 or 輸出 or 輸出 or 輸出 23. Convert real number to string with 2 decimal places Given a real number x, create its string representation s with 2 decimal digits following the dot. 給定一個實數(shù),小數(shù)點后保留兩位小數(shù)

    2024年02月16日
    瀏覽(28)
  • Rust vs Go:常用語法對比(五)

    Rust vs Go:常用語法對比(五)

    題圖來自 Rust vs Go 2023 [1] 81. Round floating point number to integer Declare integer y and initialize it with the rounded value of floating point number x . Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity). 按規(guī)則取整 2.71828 3 82. Count substring occurrences 統(tǒng)計子字符串出現(xiàn)次數(shù) 1 Disjoint ma

    2024年02月15日
    瀏覽(24)
  • Rust vs Go:常用語法對比(三)

    Rust vs Go:常用語法對比(三)

    題圖來自 When to use Rust and when to use Go [1] 41. Reverse a string 反轉字符串 輸出 or 輸出 ? roma tis r?lod müspi mérol 42. Continue outer loop Print each item v of list a which in not contained in list b. For this, write an outer loop to iterate on a and an inner loop to iterate on b. 打印列表a中不包含在列表b中的每個項目

    2024年02月16日
    瀏覽(23)
  • Rust vs Go:常用語法對比(六)

    Rust vs Go:常用語法對比(六)

    題圖來自 [1] 101. Load from HTTP GET request into a string Make an HTTP request with method GET to URL u, then store the body of the response in string s. 發(fā)起http請求 res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step. GET response: 200 Hello Inigo Montoya or or 102. Load from H

    2024年02月15日
    瀏覽(25)
  • Java VS Go 還在糾結怎么選嗎,(資深后端4000字帶你深度對比)

    Java VS Go 還在糾結怎么選嗎,(資深后端4000字帶你深度對比)

    今天我們來聊一下Go 和Java,本篇文章主要是想給對后臺開發(fā)的初學者和有意向選擇Go語言的有經(jīng)驗的程序員一些建議,希望能幫助各位自上而下的來了解一下Java和Go的全貌。 作為一個多年的Java后端開發(fā),用的時間久了就會發(fā)現(xiàn)Java語言一些問題,所謂婚前風花雪月,婚后柴米

    2024年02月04日
    瀏覽(26)
  • 【字節(jié)跳動青訓營】后端筆記整理-1 | Go語言入門指南:基礎語法和常用特性解析

    【字節(jié)跳動青訓營】后端筆記整理-1 | Go語言入門指南:基礎語法和常用特性解析

    **本人是第六屆字節(jié)跳動青訓營(后端組)的成員。本文由博主本人整理自該營的日常學習實踐,首發(fā)于稀土掘金:??Go語言入門指南:基礎語法和常用特性解析 | 青訓營 本文主要梳理自 第六屆字節(jié)跳動青訓營(后端組)-Go語言原理與實踐第一節(jié)(王克純老師主講) 。同時

    2024年02月13日
    瀏覽(24)
  • 【Rust日報】2023-02-14 Rust GUI 框架對比: Tauri vs Iced vs egui

    【Rust日報】2023-02-14 Rust GUI 框架對比: Tauri vs Iced vs egui

    Rust GUI 框架對比: Tauri vs Iced vs egui Tauri:使用系統(tǒng)的 webview 來渲染 HTML/JS 的前端。你可以選擇任何前端框架。后臺是用Rust編寫的,可以通過內(nèi)置的方法與前臺通信。 Iced: 受 Elm 啟發(fā)的(響應式)GUI庫。在桌面上使用 wgpu 進行渲染;實驗性的web后端創(chuàng)建DOM進行渲染。所有代碼

    2024年02月02日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包