struct类型匿名字段访问

时间:2014-07-20 18:30:20

标签: go

我正在努力学习golang,而我正试图理解指针。我定义了三种结构类型

type Engine struct {      
    power int             
}                         

type Tires struct {       
    number int            
}                         


type Cars struct {           
    *Engine               
    Tires                 
}       

如您所见,在Cars结构中我定义了一个匿名类型指针* Engine。看看主要的。

func main() {                    

    car := new(Cars)             
    car.number = 4               
    car.power = 342     
    fmt.Println(car)            
} 

当我尝试编译时,我发现了以下错误

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x23bb]    

如何访问电源字段?

3 个答案:

答案 0 :(得分:6)

例如,

package main

import "fmt"

type Engine struct {
    power int
}

type Tires struct {
    number int
}

type Cars struct {
    *Engine
    Tires
}

func main() {
    car := new(Cars)
    car.Engine = new(Engine)
    car.power = 342
    car.number = 4
    fmt.Println(car)
    fmt.Println(car.Engine, car.power)
    fmt.Println(car.Tires, car.number)
}

输出:

&{0x10328100 {4}}
&{342} 342
{4} 4

非限定类型名称EngineTires充当相应匿名字段的字段名称。

  

The Go Programming Language Specification

     

Struct types

     

使用类型但没有显式字段名称声明的字段是   匿名字段,也称为嵌入字段或嵌入字段   输入结构。必须将嵌入类型指定为类型名称   T或作为指向非接口类型名称* T的指针,以及T本身可以   不是指针类型。非限定类型名称充当字段   名。

答案 1 :(得分:5)

试试这个:

type Engine struct {      
    power int             
}                         

type Tires struct {       
    number int            
}                         


type Cars struct {           
    Engine               
    Tires                 
}

而不是:

car := Cars{Engine{5}, Tires{10}}
fmt.Println(car.number)
fmt.Println(car.power)

http://play.golang.org/p/_4UFFB7OVI


如果您想要指向Engine的指针,则必须将Car结构初始化为:

car := Cars{&Engine{5}, Tires{10}}
fmt.Println(car.number)
fmt.Println(car.power)

答案 2 :(得分:0)

再举一个例子,如果字段名不唯一

const findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) !== index);
    
const rearangeObject = providedObj => {
     const newObj = {};
     const keys = Object.keys(providedObj);
    
      for (let i = 0; i < keys.length; i++) {
          for (let j = i + 1; j < keys.length; j++) {
              let str = keys[i] + ", " + keys[j];
              newObj[str] = findDuplicates([...providedObj[keys[i]], ...providedObj[keys[j]]]);
          }
      }
      return newObj;
}
    
const providedObj = {
      "harsh": ["cricket", "vollyball"],
      "aasim": ["cricket", "football", "ludo", "COD", "rugb", "vollyball", "Racing"],
      "jignesh": ["cycling", "cricket"],
      "jimish": ["cycling"],
      "prince": ["vollyball", "football"],
      "raj": ["ludo", "cricket", "cycling"]
};
console.log(rearangeObject(providedObj));