resp, err := http.Get("http://kerkour.com")
if err != nil {
// ...
}
// defer resp.Body.Close() // DON'T forget this line
let wordlist_file = File::open("wordlist.txt")?;
// do something...
// we don't need to close wordlist_file
// it will be closed when the variable goes out of scope
type App struct {
mutex sync.Mutex
data map[string]string
}
func (app *App) DoSomething(input string) {
app.mutex.Lock()
defer app.mutex.Unlock()
// do something with data and input
}
func (app *App) DoManyThings(input []string) {
for _, item := range input {
app.mutex.Lock()
defer app.mutex.Unlock()
// do something with data and item
}
}
for item in input {
let _guard = mutex.lock().expect("locking mutex");
// do something
// mutex is released here as _guard is dropped
}
假设我们正在跟踪在线商店中产品的状态:
const (
StatusUnknown Status = 0
StatusDraft Status = 1
StatusPublished Status = 2
)
switch status {
case StatusUnknown:
// ...
case StatusDraft:
// ...
case StatusPublished:
// ...
}
#[derive(Debug, Clone, Copy)]
enum Platform {
Linux,
MacOS,
Windows,
Unknown,
}
impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Platform::Linux => write!(f, "Linux"),
Platform::Macos => write!(f, "macOS"),
// Compile time error! We forgot Windows and Unknown
}
}
}
据我所知,不可能在安全的 Rust 中创建对无效地址的引用。
type User struct {
// ...
Foo *Bar // is it intended to be used a a pointer, or as an optional field?
}
struct User {
// ...
foor: Option<Bar>, // it's clear that this field is optional
}
假设我们正在处理用户帐户:
type User struct {
ID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
Email string
}
func (app *App) CreateUser(email string) {
// ...
now := time.Now().UTC()
user := User {
ID: uuid.New(),
CreatedAt: now,
UpdatedAt: now,
Email: email,
}
err = app.repository.CreateUser(app.db, user)
// ...
}
struct User {
id: uuid::Uuid,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
email: String,
allowed_storage: i64,
}
fn create_user(email: String) {
let user = User {
id: uuid::new(),
created_at: now,
updated_at: now,
email: email,
// we forgot to update the function to initialize allowed_storage
};
}
From 日报小组 侯盛鑫 坏姐姐
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。