PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, December 12, 2022

[FIXED] What is the syntax and semantics of the `where` keyword?

 December 12, 2022     rust, syntax     No comments   

Issue

Unfortunately, Rust's documentation regarding where is very lacking. The keyword only appears in one or two unrelated examples in the reference.

  1. What semantic difference does where make in the following code? Is there any difference at all? Which form is preferred?

    fn double_a<T>(a: T) -> T where T: std::num::Int {
        a + a
    }
    
    fn double_b<T: std::num::Int>(a: T) -> T {
        a + a
    }
    
  2. In the implementation of the CharEq trait, it seems that where is being used as some sort of "selector" to implement Trait for anything that matches some closure type. Am I correct?

Is there any way I can get a better, more complete picture of where? (full specification of usage and syntax)


Solution

In your example, the two codes are strictly equivalent.

The where clauses were introduced to allow more expressive bound-checking, doing for example :

fn foo<T>(a: T) where Bar<T>: MyTrait { /* ... */ }

Which is not possible using only the old syntax.

Using where rather than the original syntax is generally preferred for readability even if the old syntax can still be used.

You can imagine for example constructions like

fn foo<A, B, C>(a: A, b: B, c: C)
    where A: SomeTrait + OtherTrait,
          B: ThirdTrait<A>+ OtherTrait,
          C: LastTrait<A, B>
{
    /* stuff here */
}

which are much more readable this way, even if the could still be expressed using the old syntax.

For your question about the CharEq trait, the code is:

impl<F> CharEq for F where F: FnMut(char) -> bool {
    #[inline]
    fn matches(&mut self, c: char) -> bool { (*self)(c) }

    #[inline]
    fn only_ascii(&self) -> bool { false }
}

It literally means: Implementation of trait CharEq for all type F that already implements the trait FnMut(char) -> bool (that is, a closure or a function taking a char and returning a bool).

For more details, you can look at the RFC that introduced the where clauses : https://github.com/rust-lang/rfcs/pull/135



Answered By - Levans
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing