First Or Default Null (ARCH5078)
Ce contenu n’est pas encore disponible dans votre langue.
Key go.performance.first-or-default-null · Severity warning · Category performance
Accessing [0] of a filtered slice without a length check panics when the result is empty. Add an emptiness guard before the access.
Incorrect
Section titled “Incorrect”func firstAdmin(users []User) User { admins := filter(users, isAdmin) return admins[0]}Correct
Section titled “Correct”func firstAdmin(users []User) (User, bool) { admins := filter(users, isAdmin) if len(admins) == 0 { return User{}, false } return admins[0], true}Add a len(...) == 0 check before accessing the first element.