GPHPER的菜地


  • 首页

  • 标签

  • 分类

  • 归档

rust 基础03

发表于 2024-05-19 | 分类于 rust

枚举

定义

1
2
3
4
5
6
enum Message {
Quit, // 常量标识
Move{x:i32,y:i32}, // 匿名结构体
Write(String), // 字符串
ChangeColor(i32,i32,i32) // 元组或数组数据
}

定义方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum Message {
Quit, // 常量标识
Move{x:i32,y:i32}, // 匿名结构体
Write(String), // 字符串
ChangeColor(i32,i32,i32) // 元组或数组数据
}

impl Message{
fn call(&self){}
}

fn main() {
let q = Message::Quit;
let m = Message::Move { x: 20, y: 30 };
let w = Message::Write(String::from("hello"));
let c = Message::ChangeColor(200, 300, 400);

m.call();
}

Option枚举

1
2
3
4
5
// Option的定义
enum Option<T> {
None,
Some(T),
}
1
2
3
4
5
// Option枚举用例
let some_number = Some(5);
let some_string = Some("a string");

let absent_number: Option<i32> = None;

Match 匹配

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
enum Week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

fn main() {
let num = week_num(Week::Friday);
println!("{}",num)
}

fn week_num(w:Week) -> u8{
match w {
Week::Monday => 1,
Week::Tuesday => 2,
Week::Wednesday => 3,
Week::Thursday => 4,
Week::Friday => 5,
Week::Saturday => 6,
Week::Sunday => 7,
}
}
  • 注意:match匹配的值必须进行穷举,如果没必要都匹配的话使用 _ 匹配剩余的值
    1
    2
    3
    4
    5
    6
    7
    8
    fn week_num(w:Week) -> u8{
    match w {
    Week::Monday => 1,
    Week::Tuesday => 2,
    Week::Wednesday => 3,
    _ => 0
    }
    }

使用 mat处理option枚举数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
let five = Some(5);
let _six = plus_one(five);
let _none = plus_one(None);
}

fn plus_one(x:Option<i32>)-> Option<i32> {
match x {
None => {
println!("是个空值");
None
},
Some(i) => {
println!("{}",i);
Some(i+1)
}
}
}

rust 基础

发表于 2024-05-18 | 分类于 rust

猜数游戏示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main() {
println!("猜数");

let number = rand::thread_rng().gen_range(1..100);

println!("神秘数字{}",number);

println!("请输入一个数!");

loop{
let mut guess = String::new();

// expect 处理错误信息
io::stdin().read_line(&mut guess).expect("读取数据失败");

// 类型转换 使用 match是错误处理的另一种常用方式
let guess:u32 = match guess.trim().parse(){
Ok(num) => num,
Err(_) => continue
};

println!("你猜测的数字{}",guess);

match guess.cmp(&number){
Ordering::Less => println!("偏小"),
Ordering::Equal=> {println!("赢了");break;},
Ordering::Greater=> println!("偏大")
}
}

}

变量

let 是定义变量的关键字,但是默认变量是不允许修改的,如果需要修改变量的话需要使用关键字 mut

1
2
3
4
5
let name = "cjp";
name = "gphper"; //错误

let mut name = "cjp";
name = "gphper"; //正确

变量中的 Shadow
变量可以使用let声明相同名称不同类型的变量

1
2
3
let student = "bob";
student = student.len() // 错误,因为变量不可变
let student:u32 = student.len() // 这种完成没问题

和常量的区别

  • 常量可以在任意位置定义,且必须声明类型 const MAX_NUM:u32 = 20;
  • 常量一旦定义不能修改

数据类型

标量

*整型、浮点型、字符型、布尔型

复合类型

tuple 类型:可以由多个不同类型的值组成

1
2
3
4
5
6
7
8
9
10
11
fn main() {
let t:(i32,f64,&str) = (10,3.4,"hello");

// 直接访问
println!("{},{},{}",t.0,t.1,t.2);

// 分别赋值访问
let(x,y,z) = t;

println!("{},{},{}",x,y,z);
}

数组类型:由相同类型的值组成

1
2
3
4
5
6
// 正常生成数组类型
let arr:[i32;5] = [1,2,3,4,6];
println!("Array {:?}", arr);
// 也可以这样生成数组中元素值一致的数组
let arr1 = [3;5];
println!("Array {:?}",arr1);

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
fn main() {
show(3);
let result = show_data();
println!("{}",result);
}

fn show(x:i32){
println!("{}",x)
}

fn show_data() -> i32 {
5 // 返回值不能加 ;
}
  • 注意返回值的书写方式

if 语句

1
2
3
4
5
6
let m = 3;
if m > 3{
println!("大于3");
}else{
println!("小于等于3");
}

if属于表达式,所以可以为变量赋值

1
2
let number = if m == 3 { 3 } else { 0 };
println!("最后的数值是{}",number);

循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
let mut count = 0;

// 注意loop可以在break处赋值
let result = loop{
count += 1;
if count == 10{
break count*2;
}
};
println!("result 结果{}",result);

let mut m = 10;
while m > 1{
println!("m is {}",m);
m -= 1;
}

let arr = [1,2,3,4,5];
for item in arr.iter(){
println!("array item is {}",item);
}

// 使用range
for ritem in (1..4).rev(){
println!("range item is {}",ritem);
}

}

rust 基础02

发表于 2024-05-18 | 分类于 rust

所有权

规则

  • Rust 中的每个值都有一个变量,称为其所有者。
  • 一次只能有一个所有者。
  • 当所有者不在程序运行范围时,该值将被删除。

移动和克隆

移动

  • 对于基础类型的数据,移动就是进行复制
    1
    2
    3
    4
    5
    6
    fn main() {
    let x = 5;
    let y = x;

    println!("{},{}",x,y); // x,y都有效
    }
  • 需要在堆上分配内存的数据类型
    1
    2
    3
    4
    5
    6
    fn main() {
    let x = String::from("hello world");
    let y = x;

    println!("{},{}",x,y); // x作废了,只有y有效 borrow of moved value: `x`
    }
  • 解决第二种情况的方法是使用克隆
    1
    2
    3
    4
    5
    6
    7
    fn main() {
    let x = String::from("hello world");
    let xx = x.clone();
    let y = x;

    println!("{},{}",xx,y);
    }

    在函数中的使用

    作为参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    fn main() {
    let x = String::from("hello world");
    show_str(x); // x移动到了函数里面,所以x的作用域在往下就失效了

    println!("{}",x); // x失效了

    let m = 10;
    show_int(m); // m也是移动到了函数中,但是基础类型的变量的分配是在栈里面,这里的移动本质上是复制,所以m在下面的作用域中还是有效了
    println!("{}",m);

    let str = String::from("gphper");
    show(&str); // 使用引用的方式可以保证,函数外面的变量不会失效
    println!("{}",str);
    }

    fn show_str(str:String){
    println!("{}",str);
    }

    fn show_int(i:i32) {
    println!("{}",i);
    }

    fn show(str:&String){
    println!("{}",*str);
    }

切片

1
2
3
4
5
6
7
8
fn main() {
let s = String::from("broadcast");

let s1 = &s[1..2];
let s2 = &s[3..4];

println!("{}+{}",s1,s2);
}

结构体

Struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
struct Student{
username:String,
sex:String,
score:u32
}

let mut s = Student{
username:String::from("gphper"),
sex:String::from("男"),
score:100
};

s.score = 200;

println!("{},{},{}",s.username,s.sex,s.score);
}

结构体打印调试的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fn main() {

#[derive(Debug)]
struct Student{
username:String,
sex:String,
score:u32
}

let mut s = Student{
username:String::from("gphper"),
sex:String::from("男"),
score:100
};

s.score = 100;

println!("{:#?}",s);
println!("{},{},{}",s.username,s.sex,s.score);
}

Tuple Struct

  • 为元组类型添加一个名称标识
    1
    2
    3
    4
    5
    6
    7
    fn main() {
    struct Student(String,String,u32);

    let s = Student(String::from("gphper"),String::from("男"),200);

    println!("{},{},{}",s.0,s.1,s.2);
    }

    结构体的方法和关联函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    #[derive(Debug)]
    struct Rectangle {
    width: u32,
    height: u32,
    }

    impl Rectangle {

    // 方法
    fn area(&self) -> u32{
    self.width * self.height
    }

    // 关联函数
    fn square(size:u32) -> Rectangle{
    Rectangle { width: size, height: size }
    }
    }

    fn main() {
    let r = Rectangle{width:20,height:30};
    let area = r.area();
    println!("{}",area);

    let square = Rectangle::square(20);
    println!("{:#?}",square);
    }

SSM[spring] 基于xml的AOP使用

发表于 2023-12-30 | 分类于 SSM

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
阅读全文 »

SSM[spring] 基于XML的IOC使用

发表于 2023-12-30 | 分类于 SSM

Bean的注意事项

创建bean的三种方式

  • 使用默认构造函数
    1
    <bean id="accountService" class="com.gphper.service.imp.AccountServiceImpl"></bean>
  • 使用其他类提供的方法获取对象
    1
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
  • 使用其他类中的静态方法创建
    1
    <bean id="accountService" class="instanceFactory" factory-method="getAccountService"></bean>
    阅读全文 »

SSM[spring] 基于注解的AOP使用

发表于 2023-12-30 | 分类于 SSM

示例代码

[AccountServiceImp]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.gphper.Imp;

import com.gphper.IAccountService;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImp implements IAccountService {
@Override
public void saveAccount() {
System.out.println("保存账号成功");
}

@Override
public void updateAccount(int i) {
System.out.println("更新账号id"+i);
}

@Override
public void deleteAccount() {
System.out.println("删除账号成功");
}
}

阅读全文 »

SSM[spring] 基于注解的IOC使用

发表于 2023-12-30 | 分类于 SSM

注解模式注意点

  • xml文件的头信息和引用类的方式有区别
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.gphper"></context:component-scan>
    </beans>
  • 注解的使用方式和基于xml的使用方式是可以混合使用的

<bean> 标签的替代注解 Component

  • 不取名字时,默认设置为 首字母小写的类的名称
  • 还有三个平替注解 Controller 表现层 Service 业务层 Repository 持久层 效果及使用和 Component 注解一样

注入数据标签

  • Autowired 自动按照类型注入,如果IOC中有多个相同类型的对象时,会按照成员变量的名称寻找。可以配合 Qualifier 注解指定多个相同类型对象中的对象id
  • Resource 注解 直接指定id注入指定的成员中
  • 以上标签只能注入 bean 类型的数据,基本类型和String类型的不能使用,注解不支持集合类型的数据注入只能使用xml格式的写法
  • Value 注解作用于基本类型和String类型,且支持SpEl表达式 ${表达式}

范围注解

  • Scope 注解,设置类的作用范围,常用的单例和多例 singleton prototype

生命周期相关注解

  • PreDestory 相当于 destory-method 属性 PostConstruct 相当于 init-method
[com.gphper.service.imp.AccountServiceImpl]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.gphper.service.imp;

import com.gphper.dao.IAccountDao;
import com.gphper.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AccountServiceImpl implements IAccountService {

// @Autowired
// @Qualifier("accountDao")
@Resource(name = "accountDao")
private IAccountDao account;

@Value("gphper")
private String username;

@Override
public void saveAccount() {
account.saveAccount();
}

@Override
public String toString() {
return "AccountServiceImpl{" +
"username='" + username + '\'' +
'}';
}
}
[package com.gphper.dao.impl.AccountDao]
1
2
3
4
5
6
7
8
9
10
11
package com.gphper.dao.impl;

import com.gphper.dao.IAccountDao;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDao implements IAccountDao {
public void saveAccount(){
System.out.println("保存成功");
}
}

完全去除xml

  • Configuration 声明配置类
  • ComponentScan 配置Bean加载包的路径
  • Bean 将方法的返回值注入到IOC容器中
  • Import 在注解类中引入其他注解
  • PropertySource 指定properties配置文件
1
2
3
4
5
6
7
<bean id="stat" factory-bean="conn" factory-method="createStatement"></bean>

<bean id="conn" class="java.sql.DriverManager" factory-method="getConnection">
<constructor-arg name="url" value="jdbc:mysql://localhost:3306/book?useSSL=false"></constructor-arg>
<constructor-arg name="user" value="root"></constructor-arg>
<constructor-arg name="password" value="123456"></constructor-arg>
</bean>
[配置文件类]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.gphper.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@Configuration
@ComponentScan("com.gphper")
@PropertySource("jdbc.properties") // 指定properties文件
public class SpringConfig {

@Value("${jdbc.url}")
private String url;
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;

@Bean("conn")
public Connection getConn() throws SQLException {
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}

@Bean("stat")
public Statement getStat(Connection conn) throws SQLException {
Statement stat = conn.createStatement();
return stat;
}

}
1
2
3
// ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
// 替换主程序实现类
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);

SSM[mybaits] CURD

发表于 2023-12-24 | 分类于 SSM

CRUD xml操作

[com.gphper.dao.IUserDAo]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.gphper.dao;

import com.gphper.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface IUserDAo {
/**
* 查询操作
* @return
*/
List<User> findAll();

/**
* 新增操作
* @param user
*/
void saveUser(User user);

/**
* 更新
* @param user
*/
void updateUser(User user);

/**
* 删除
* @param uid
*/
void deleteUser(Integer uid);

/**
* 根据id查询
* @param uid
* @return
*/
User findById(Integer uid);

/**
* 根据名称模糊查询
* @param name
* @return
*/
List<User> findByName(String name);

/**
* 查询条数
* @return
*/
int findCount();
}
阅读全文 »

SSM[mybaits] 复杂查询

发表于 2023-12-24 | 分类于 SSM

动态sql语句

  • <where> 和 <if>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <select id="findByCond" resultType="com.gphper.domain.User" parameterType="com.gphper.domain.User">
    select * from user
    <where>
    <if test="name != null">
    and name = #{name}
    </if>
    <if test="gender != null">
    and gender = #{gender}
    </if>
    </where>
    </select>
    [IUserDao.java]
    1
    List<User> findByCond(User user);
    [测试方法]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public void findByCond(){
    User u = new User();
    u.setName("cjp");
    u.setGender("男");
    List<User> users = userDao.findByCond(u);
    for(User user:users){
    System.out.println(user);
    }
    }
    阅读全文 »

SSM[mybaits] 搭建和入门

发表于 2023-12-24 | 分类于 SSM

环境搭建

  1. 创建 maven 工程

  2. 创建实体类和dao接口

    [User.java]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    package com.gphper.domain;

    import java.util.Date;

    public class User {
    int id;
    String number;
    String name;
    String password;
    String gender;
    Date create_time;
    Date update_time;
    int sex;

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getNumber() {
    return number;
    }

    public void setNumber(String number) {
    this.number = number;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public String getGender() {
    return gender;
    }

    public void setGender(String gender) {
    this.gender = gender;
    }

    public Date getCreate_time() {
    return create_time;
    }

    public void setCreate_time(Date create_time) {
    this.create_time = create_time;
    }

    public Date getUpdate_time() {
    return update_time;
    }

    public void setUpdate_time(Date update_time) {
    this.update_time = update_time;
    }

    public int getSex() {
    return sex;
    }

    public void setSex(int sex) {
    this.sex = sex;
    }

    @Override
    public String toString() {
    return "User{" +
    "id=" + id +
    ", number='" + number + '\'' +
    ", name='" + name + '\'' +
    ", password='" + password + '\'' +
    ", gender='" + gender + '\'' +
    ", create_time=" + create_time +
    ", update_time=" + update_time +
    ", sex=" + sex +
    '}';
    }
    }

    阅读全文 »
12…4>

33 日志
6 分类
12 标签
© 2024 GPHPER
由 Hexo 强力驱动
|
主题 — NexT.Mist v5.1.4