Home > other >  Two questions about the language grammar
Two questions about the language grammar

Time:11-18

Looking at this page, I met two problems: https://studygolang.com/articles/22460

Question 1:

See a function is defined like this:
 
Func (fd * fd) Read (p byte []) (int, error) {
If err:=fd readLock (); err ! Nil={
Return 0, err
}
.
}


(p byte []) is a parameter, (int, error) is the return value type, * fd (fd) is what?


Question 2:

 
Func handleConnection (conn net. Conn) {
Defer conn. Close ()
Var body [4] byte
Addr:=conn. RemoteAddr ()
For {
//read the client message
_, err:=conn. Read (body [:])
if err ! Nil={
Break
}
FMT. Printf (" message received % s: % s \ n ", addr, string (body [:]))
//return package
_, err=conn. Write (body [:])
if err ! Nil={
Break
}
FMT. Printf (" sent to % s: % s \ n ", addr, string (body [:]))
}
FMT. Printf (" disconnect with % s! \ n ", addr)
}


_, err:=conn. Read (body [:]) in the statement [:] what do you mean? A colon in the brackets,


CodePudding user response:

1: * fd (fd) method is a receiver, in general is a struct, of course, may also be a type fd struct such custom type, look at the specific you find source, said popular point, you can think * fd realized (receive) the Read method, pay attention to the fd is * and not fd, fd (fd) is the fd,
2: [:] said intercept all body array data similar to the body [4-0]

CodePudding user response:

2: [:] said to intercept all body array data, equivalent to the body [4-0], note after [:], interception of data is a slice, is no longer an array,

CodePudding user response:

1 is not quite right, originally type FD struct is to define structure of syntax, type FD int, this example is more appropriate,

CodePudding user response:

The two problems are the basic grammar problems, serious look at the grammar is easy to understand,
1, define a structure, the method of fd * fd is to define a structure member, implements an interface of the Read method (inheritance can be thought of as the interface)
2, the body [:] is to return a slice (sliced), the colon is two leading index, omit don't write is the default minimum or maximum boundary,
  • Related