What is the difference between a const variable and a static variable and which should I choose?

前端 未结 3 1996
借酒劲吻你
借酒劲吻你 2020-12-03 21:46

I know this from RFC 246:

  • constants declare constant values. These represent a value, not a memory address. This is
3条回答
  •  时光说笑
    2020-12-03 22:31

    The main purpose of static is to allow functions to control an internal value that is remembered across calls, but not be accessible by the main application code. It is similar to Class variables as opposed to Instance variables in other languages. Also C and PHP and many other languages have this concept.

    Example: you want to track how many times a function is called and have a way of resetting the internal counter:

    fn counter(reset: bool) -> i32 {
        static mut Count: i32 = 0;
    
        unsafe {
            if reset {
                Count = 0;
            }    
            Count += 1;
            return Count;
        }
    }
    
    println!("{}",counter(true));
    println!("{}",counter(false));
    println!("{}",counter(false));
    //println!("{}", Count); // Illegal
    

提交回复
热议问题