Movatterモバイル変換


[0]ホーム

URL:


where

Keywordwhere 

Source
Expand description

Add constraints that must be upheld to use an item.

where allows specifying constraints on lifetime and generic parameters.TheRFC introducingwhere contains detailed information about thekeyword.

§Examples

where can be used for constraints with traits:

fnnew<T: Default>() -> T {    T::default()}fnnew_where<T>() -> TwhereT: Default,{    T::default()}assert_eq!(0.0, new());assert_eq!(0.0, new_where());assert_eq!(0, new());assert_eq!(0, new_where());

where can also be used for lifetimes.

This compiles becauselonger outlivesshorter, thus the constraint isrespected:

fnselect<'short,'long>(s1:&'shortstr, s2:&'longstr, second: bool) ->&'shortstrwhere'long:'short,{ifsecond { s2 }else{ s1 }}letouter = String::from("Long living ref");letlonger =&outer;{letinner = String::from("Short living ref");letshorter =&inner;assert_eq!(select(shorter, longer,false), shorter);assert_eq!(select(shorter, longer,true), longer);}

On the other hand, this will not compile because thewhere 'b: 'a clauseis missing: the'b lifetime is not known to live at least as long as'awhich means this function cannot ensure it always returns a valid reference:

fnselect<'a,'b>(s1:&'astr, s2:&'bstr, second: bool) ->&'astr{ifsecond { s2 }else{ s1 }}

where can also be used to express more complicated constraints that cannotbe written with the<T: Trait> syntax:

fnfirst_or_default<I>(muti: I) -> I::ItemwhereI: Iterator,    I::Item: Default,{    i.next().unwrap_or_else(I::Item::default)}assert_eq!(first_or_default([1,2,3].into_iter()),1);assert_eq!(first_or_default(Vec::<i32>::new().into_iter()),0);

where is available anywhere generic and lifetime parameters are available,as can be seen with theCow type from the standardlibrary:

pub enumCow<'a, B>whereB: ToOwned +?Sized,{    Borrowed(&'aB),    Owned(<BasToOwned>::Owned),}

[8]ページ先頭

©2009-2026 Movatter.jp