diff --git a/doc/docs.md b/doc/docs.md index 2b79ef2bb2..6a0372da66 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -97,7 +97,7 @@ by using any of the following commands in a terminal: * [Trailing struct literal arguments](#trailing-struct-literal-arguments) * [Access modifiers](#access-modifiers) * [Anonymous structs](#anonymous-structs) - * [Static type methods](#static-type-methods) + * [Static type methods](#static-type-methods) * [[noinit] structs](#noinit-structs) * [Methods](#methods) * [Embedded structs](#embedded-structs) @@ -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 diff --git a/vlib/v/parser/fn.v b/vlib/v/parser/fn.v index 83860b7e5c..76bff1a659 100644 --- a/vlib/v/parser/fn.v +++ b/vlib/v/parser/fn.v @@ -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 { diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index b4a878d9fe..3f8d811364 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -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}'