Rust具有带状态的匿名闭包。我可以对命名函数做同样的事情吗?
(无效的伪代码)
fn counting_function()->i32 {
let mut static counter = 0;
counter = counter + 1;
return counter.clone();
}
我知道我可以使用结构和函数/特征来做到这一点。我知道迭代器是执行此操作的正确方法。但是将结构留给特征和迭代器,我可以做到这一点而无需将任何(初始化结构)负担转移给调用者吗?
答案 0 :(得分:2)
这是使用原子的线程安全变体:
use std::sync::atomic::{AtomicUsize, Ordering};
fn counting_function() -> usize {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let result = COUNTER.fetch_add(1, Ordering::Relaxed);
result
}
但这实际上是一种代码气味。
答案 1 :(得分:-2)
您的伪代码几乎可以正常工作。要使用security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
#anonymous: true
guard:
authenticators:
- App\Security\LdapCustomAuthenticator
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY}
# You can use it also for different roles, maybe you need also route for all check comments (be careful with order)
#- { path: ^/admin, roles: ROLE_ADMIN}
#- { path: ^/, roles: ROLE_USER}
变量,您需要将对代码的访问和修改部分标记为static mut
,因为这些操作不是线程安全的。
unsafe