在使用以下内容测试某些代码时:
// ch := make(chan error)
for {
select {
case <- ch:
println("here")
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到如果我不添加default代码块:
for {
select {
case <- ch:
println("here")
default:
}
}
Run Code Online (Sandbox Code Playgroud)
如果块是必需的,那么就可以使用range,例如:
for {
for _ = range <- ch {
println("here")
}
}
Run Code Online (Sandbox Code Playgroud)
或者select在range这种情况下使用结束有什么不同/优势?
使用Go what 包、本地函数、系统调用可用于获取*nix 系统上的默认网关
我想避免创建包装器 arround netstat、路由、 ip 等命令,或读取、解析现有文件,其想法是获取最可能的操作系统/平台不可知方式的值。
例如,这是route命令的输出:
$ route -n get default
route to: default
destination: default
mask: default
gateway: 192.168.1.1
interface: en1
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1500 0
Run Code Online (Sandbox Code Playgroud)
我想做一些类似的事情,以便只打印/获取网关地址/接口。
在Raspberry Pi 1 model B上,我使用 SD 卡映像RPI-B安装了FreeBSD 10.3。
我可以启动、获取网络、通过 ssh 进入等等,一切似乎都正常且功能正常。这是 dmesg 输出的一部分:
FreeBSD 10.3-RELEASE #0 r297264: Fri Mar 25 08:01:14 UTC 2016
root@releng1.nyi.freebsd.org:/usr/obj/arm.armv6/usr/src/sys/RPI-B arm
FreeBSD clang version 3.4.1 (tags/RELEASE_34/dot1-final 208032) 20140512
VT: init without driver.
CPU: ARM1176JZ-S rev 7 (ARM11J core)
Supported features: ARM_ISA THUMB2 JAZELLE ARMv4 Security_Ext
WB enabled LABT branch prediction enabled
16KB/32B 4-way instruction cache
16KB/32B 4-way write-back-locking-C data cache
real memory = 503312384 (479 MB)
avail memory = 483127296 (460 …Run Code Online (Sandbox Code Playgroud) 我想按需取消正在运行的命令,为此,我正在尝试exec.CommandContext,目前正在尝试:
https://play.golang.org/p/0JTD9HKvyad
package main
import (
"context"
"log"
"os/exec"
"time"
)
func Run(quit chan struct{}) {
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, "sleep", "300")
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
go func() {
log.Println("waiting cmd to exit")
err := cmd.Wait()
if err != nil {
log.Println(err)
}
}()
go func() {
select {
case <-quit:
log.Println("calling ctx cancel")
cancel()
}
}()
}
func main() {
ch := make(chan struct{})
Run(ch)
select {
case …Run Code Online (Sandbox Code Playgroud) 我的目标是同时运行 N 个函数,但在所有函数完成之前不想生成更多函数。这是我到目前为止所拥有的:
extern crate tokio;
extern crate futures;
use futures::future::lazy;
use std::{thread, time};
use tokio::prelude::*;
use tokio::timer::Interval;
fn main() {
let task = Interval::new(time::Instant::now(), time::Duration::new(1, 0))
.for_each(|interval| {
println!("Interval: {:?}", interval);
for i in 0..5 {
tokio::spawn(lazy(move || {
println!("Hello from task {}", i);
// mock delay (something blocking)
// thread::sleep(time::Duration::from_secs(3));
Command::new("sleep").arg("3").output().expect("failed to execute process");
Ok(())
}));
}
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e));
tokio::run(task);
}
Run Code Online (Sandbox Code Playgroud)
我每秒生成 5 个函数,但现在我想等到所有函数完成后再生成更多函数。
根据我的理解(我的想法可能是错误的),我将Future 在另一个未来返回
extern crate tokio;
extern …Run Code Online (Sandbox Code Playgroud) 如何根据进程启动后发生的事件/条件正确设置/修改值,同时在不创建竞争条件的情况下处理Goroutine。
例如,以下“有效(有问题)”,输出为:
ping, foo=true
ping, foo=false
ping, foo=true
ping, foo=true
ping, foo=true
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/Y3FafF-nBc
ping, foo=true
ping, foo=false
ping, foo=true
ping, foo=true
ping, foo=true
Run Code Online (Sandbox Code Playgroud)
但是如果使用-race选项编译或运行,我会得到这个输出:
$ go run -race main.go
ping, foo=true
==================
WARNING: DATA RACE
Write at 0x00c4200761b8 by goroutine 6:
main.(*test).run()
/main.go:16 +0x1fb
Previous read at 0x00c4200761b8 by main goroutine:
main.main()
/main.go:37 +0x5e
Goroutine 6 (running) created at:
main.New()
/main.go:30 +0xd0
main.main()
/main.go:35 +0x33
==================
ping, foo=false
ping, foo=true
ping, foo=true
ping, foo=true
Found 1 …Run Code Online (Sandbox Code Playgroud) 如果我想填充一个字符串,我可以使用这样的东西:
https://play.golang.org/p/ATeUhSP18N
package main
import (
"fmt"
)
func main() {
x := fmt.Sprintf("%+20s", "Hello World!")
fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)
+ always print a sign for numeric values;
guarantee ASCII-only output for %q (%+q)
- pad with spaces on the right rather than the left (left-justify the field)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想动态更改打击垫大小,我怎么能传递该值?
我的第一位客人是:
x := fmt.Sprintf("%+%ds", 20, "Hello World!")
Run Code Online (Sandbox Code Playgroud)
但我明白了:
%ds%!(EXTRA int=20, string=Hello World!)
Run Code Online (Sandbox Code Playgroud)
有没有办法在不创建自定义填充函数的情况下执行此操作,可能会使用for循环向左或向右添加空格:
for i := 0; i < n; i++ {
out += str
}
Run Code Online (Sandbox Code Playgroud) 我需要为超过1GB的文件计算sha256校验和(通过块读取文件),目前我正在使用python:
import hashlib
import time
start_time = time.time()
def sha256sum(filename="big.txt", block_size=2 ** 13):
sha = hashlib.sha256()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
sha.update(chunk)
return sha.hexdigest()
input_file = '/tmp/1GB.raw'
print 'checksum is: %s\n' % sha256sum(input_file)
print 'Elapsed time: %s' % str(time.time() - start_time)
Run Code Online (Sandbox Code Playgroud)
我想尝试golang认为我可以获得更快的结果,但在尝试下面的代码后,它运行慢了几秒钟:
package main
import (
"crypto/sha256"
"fmt"
"io"
"math"
"os"
"time"
)
const fileChunk = 8192
func File(file string) string {
fh, err := os.Open(file)
if err != nil {
panic(err.Error()) …Run Code Online (Sandbox Code Playgroud) 在Go中,要检查字符串是否为空,可以使用:
len(str) == 0
Run Code Online (Sandbox Code Playgroud)
要么
len(str) < 1
Run Code Online (Sandbox Code Playgroud)
要么
str == ""
Run Code Online (Sandbox Code Playgroud)
基本上只是一个选择的运营商的计==,<,!=,但在性能愿望的选择是更好的条件?
我的猜测是,==只是比较并且不迭代这些值,<或者任何一个<==都可以做,因此想知道什么是最好的方法练习.
在许多编程语言中,可以通过在模式位和之间执行按位与操作来确定文件是否可执行,如下所示:0111
is_exec = (mode & 0111) != 0
Run Code Online (Sandbox Code Playgroud)
其中mode表示模式位,其八进制值类似于100755, 或755。
命令行示例:
perl -e 'printf "%o\n", (stat "file")[2] & 0111'
Run Code Online (Sandbox Code Playgroud)
我试图使用 Rust 遵循这种方法,但无法使其工作,这是我正在使用的代码:
fn print_dir(path: &PathBuf) {
let files = match fs::read_dir(&path) {
Err(f) => {
println!("{}", f);
return;
}
Ok(f) => f
};
for f in files {
let file = f.unwrap();
let mode = file.metadata().unwrap().permissions().mode();
println!("path: {} {:o} - {} {:0}", file.path().display(), mode, mode, mode & 0111);
}
} …Run Code Online (Sandbox Code Playgroud) 为了减少代码行数,我将拍手 App移动到另一个文件,如下所示:
use clap::{App, AppSettings, Arg, ArgMatches}; // 2.33.3
use std::path::Path;
fn main() {
let s3m_dir = Path::new("/tmp").join(".s3m");
let matches = get_matches(s3m_dir.display().to_string());
println!("{:#?}", matches);
}
pub fn get_matches(home_dir: String) -> ArgMatches<'static> {
App::new("s3m")
.version(env!("CARGO_PKG_VERSION"))
.setting(AppSettings::SubcommandsNegateReqs)
.after_help(format!("foo bar: {}", home_dir).as_ref())
.arg(
Arg::with_name("config")
.help("config.yml")
.long("config")
.short("c")
.default_value(&format!("{}/.s3m/config.yml", home_dir))
.required(true)
.value_name("config.yml"),
)
.get_matches()
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我不知道如何使用参数home_dir作为default_value, 这里:
.default_value(&format!("{}/.s3m/config.yml", home_dir))
Run Code Online (Sandbox Code Playgroud)
default_value的签名是:
pub fn default_value(self, val: &'a str) -> Self
Run Code Online (Sandbox Code Playgroud)
我怎样才能通过一个format!("{}/.s3m/config.yml", home_dir与其他人的一生来满足签名?
go ×9
rust ×3
performance ×2
checksum ×1
clap ×1
coredump ×1
freebsd ×1
networking ×1
printf ×1
python ×1
rust-tokio ×1
system-calls ×1