• Go数组和切片定义和初始化


    1 前言

    切片是动态数组,数组数组是按值赋值,切片是按地址赋值(引用)

    2 代码

    2.1 数组初始化

    func basic_array(){
    	//var arr2 = [3]int{2,4,6} // 1
    
    	//arr2 := [3]int{2,4,6} //2
    		
    	//var arr2[3]int = [3]int{2,4,6} //3
    
    	//var arr2 [3]int  //4
    	//arr2=[3]int{1,3,5}
    
    	// var arr2 [3]int //5
    	// var i int
    	// for i=0;i<len(arr2);i++{
    	// 	arr2[i] = 10+i;
    	// }
    
            // var arr2 [3]int //6
            // var arr2 [...]int{1,3,7} //7[...]表示根据元素自适应大小
    
    
    
        for i,e := range arr2{
    		fmt.Println("arr2[",i,"]->",e);
    	}
    }
    

    2.2 切片初始化

    func basic_slice(){
    
    	//var arr2 = []int{2,4,6} // 1
    
    	//arr2 := []int{2,4,6} //2
    		
    	//var arr2[]int = [3]int{2,4,6} //3
    
    	//var arr2 []int  //4
    	//arr2=[]int{1,3,5}
    
           //var slice1 []type = make([]type, len) //5
        //slice1 := make([]type, len) //6
        //also add parameter capacity
        //make([]T, length, capacity) //7,8
    
    	for i,e := range arr2{
    		fmt.Println("arr2[",i,"]->",e);
    	}
    
    }
    

    3 数组与切片区别

    var arr2[3]int = [3]int{2,4,6}
    	var arr1 = arr2
    	arr1[1]=11
    
    	for i,e := range arr1{
    		fmt.Println("arr1[",i,"]->",e);
    	}
    
    	for i,e := range arr2{
    		fmt.Println("arr2[",i,"]->",e);
    	}
    
    //result
    // arr1[ 0 ]-> 2
    // arr1[ 1 ]-> 11
    // arr1[ 2 ]-> 6
    // arr2[ 0 ]-> 2
    // arr2[ 1 ]-> 4
    // arr2[ 2 ]-> 6
    
    
    
    //slice
    var arr2[]int = []int{2,4,6}
    	var arr1 = arr2
    	arr1[1]=11
    
    	for i,e := range arr1{
    		fmt.Println("arr1[",i,"]->",e);
    	}
    
    	for i,e := range arr2{
    		fmt.Println("arr2[",i,"]->",e);
    	}
    
    //result
    // arr1[ 0 ]-> 2
    // arr1[ 1 ]-> 11
    // arr1[ 2 ]-> 6
    // arr2[ 0 ]-> 2
    // arr2[ 1 ]-> 11
    // arr2[ 2 ]-> 6
    

      

      

      

  • 相关阅读:
    Servlet监听器及在线用户
    数据分页jdbc+mysql实现
    使用ajax验证用户名重复
    Mysql中的事务
    用户登录注册案例分析
    Java连接mysql数据库
    Java连接sqlite数据库
    虚拟主机TOMCAT配置
    用jquery控制表格奇偶行及活动行颜色
    JDK安装后 没有tools.jar 和dt.jar包的解决办法
  • 原文地址:https://www.cnblogs.com/fanbi/p/10021586.html
Copyright © 2020-2023  润新知