1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

doc: clarify new static type methods a bit

This commit is contained in:
Alexander Medvednikov 2023-06-27 01:38:31 +03:00
parent d52bac8ee9
commit 21ccb9b48e
3 changed files with 14 additions and 7 deletions

View File

@ -2435,16 +2435,24 @@ assert book.author.age == 24
### Static type methods
V now supports static type methods like `User.new()`. These are defined on a struct via
`fn [Type name].[function name] and allow to organize all functions related to a struct:
`fn [Type name].[function name]` and allow to organize all functions related to a struct:
```v oksyntax
struct User { }
fn User.new() User { return User{} }
fn User.new() User {
return User{}
}
user := User.new()
```
This is an alternative to factory functions like `fn new_user() User {}` and should be used
instead.
Note, that these are not constructors, but simple functions. V doesn't have constructors or
classes.
### `[noinit]` structs
V supports `[noinit]` structs, which are structs that cannot be initialised outside the module

View File

@ -1,6 +1,6 @@
// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that ca be found in the LICENSE file.
// that can be found in the LICENSE file.
module parser
import v.ast
@ -299,7 +299,7 @@ fn (mut p Parser) fn_decl() ast.FnDecl {
&& p.peek_tok.kind == .dot && language == .v // `fn Foo.bar() {}`
if is_static_type_method {
type_name := p.tok.lit // "Foo"
rec.typ = p.parse_type() //_with_mut(false) // ast.Type(p.table.find_type_idx(name))
rec.typ = p.parse_type()
p.check(.dot)
name = type_name.to_lower() + '__static__' + p.check_name() // "foo__bar"
} else {

View File

@ -2593,7 +2593,6 @@ fn (mut p Parser) name_expr() ast.Expr {
is_generic_call := p.is_generic_call()
is_generic_cast := p.is_generic_cast()
is_generic_struct_init := p.is_generic_struct_init()
// mut is_static_type_method := false
// p.warn('name expr $p.tok.lit $p.peek_tok.str()')
same_line := p.tok.line_nr == p.peek_tok.line_nr
// `(` must be on same line as name token otherwise it's a ParExpr
@ -2675,7 +2674,7 @@ fn (mut p Parser) name_expr() ast.Expr {
return node
} else {
// fn call
// fn_call:
// fn_call
if is_option {
p.unexpected_with_pos(p.prev_tok.pos(),
got: '${p.prev_tok}'